JavaScript + jQuery + XHR + http + SuperAgent (#561)

This commit is contained in:
Boris Verkhovskiy 2023-06-07 17:04:51 +01:00 committed by GitHub
parent 66fdc3c88c
commit 2cc2b34274
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
127 changed files with 3062 additions and 140 deletions

View File

@ -6,10 +6,10 @@ insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
[*.js]
[{*.ts, *.js, *.json, *.yml}]
indent_style = space
indent_size = 2
[{package.json,*.yml,*.cjson}]
[{*.py}]
indent_style = space
indent_size = 2
indent_size = 4

View File

@ -91,10 +91,11 @@ Choose the output language by passing `--language <language>`. The options are
- `http`
- `httpie`
- `java`, `java-httpurlconnection`, `java-okhttp`
- `javascript`, `node`, `node-axios`, `node-got`, `node-request`
- `javascript`, `javascript-jquery`, `javascript-xhr`
- `json`
- `kotlin`
- `matlab`
- `node`, `node-http`, `node-axios`, `node-got`, `node-request`, `node-superagent`
- `php`, `php-guzzle`, `php-requests`
- `python` (the default)
- `r`

View File

@ -150,7 +150,7 @@ export interface Request {
unixSocket?: Word;
netrc?: "optional" | "required" | "ignored"; // undefined means implicitly "ignored"
// These are global options
// Global options
verbose?: boolean;
silent?: boolean;
}
@ -185,7 +185,6 @@ function buildURL(
}
}
// TODO: remove .originalQuery
const urlWithOriginalQuery = mergeWords([
u.scheme,
"://",

View File

@ -34,6 +34,14 @@ import {
_toJavaScript,
toJavaScriptWarn,
} from "./generators/javascript/javascript.js";
import {
_toJavaScriptJquery,
toJavaScriptJqueryWarn,
} from "./generators/javascript/jquery.js";
import {
_toJavaScriptXHR,
toJavaScriptXHRWarn,
} from "./generators/javascript/xhr.js";
import { _toJsonString, toJsonStringWarn } from "./generators/json.js";
import { _toKotlin, toKotlinWarn } from "./generators/kotlin.js";
import { _toMATLAB, toMATLABWarn } from "./generators/matlab/matlab.js";
@ -43,10 +51,15 @@ import {
toNodeAxiosWarn,
} from "./generators/javascript/axios.js";
import { _toNodeGot, toNodeGotWarn } from "./generators/javascript/got.js";
import { _toNodeHttp, toNodeHttpWarn } from "./generators/javascript/http.js";
import {
_toNodeRequest,
toNodeRequestWarn,
} from "./generators/javascript/request.js";
import {
_toNodeSuperAgent,
toNodeSuperAgentWarn,
} from "./generators/javascript/superagent.js";
import { _toPhp, toPhpWarn } from "./generators/php/php.js";
import { _toPhpGuzzle, toPhpGuzzleWarn } from "./generators/php/guzzle.js";
import {
@ -95,23 +108,34 @@ const translate: {
],
"java-okhttp": [_toJavaOkHttp, toJavaOkHttpWarn],
javascript: [_toJavaScript, toJavaScriptWarn],
"javascript-fetch": [_toJavaScript, toJavaScriptWarn], // undocumented alias
"javascript-axios": [_toNodeAxios, toNodeAxiosWarn], // undocumented alias
"javascript-fetch": [_toJavaScript, toJavaScriptWarn], // undocumented alias
"javascript-got": [_toNodeGot, toNodeGotWarn], // undocumented alias
"javascript-jquery": [_toJavaScriptJquery, toJavaScriptJqueryWarn],
"javascript-request": [_toNodeRequest, toNodeRequestWarn], // undocumented alias
"javascript-superagent": [_toNodeSuperAgent, toNodeSuperAgentWarn], // undocumented alias
"javascript-xhr": [_toJavaScriptXHR, toJavaScriptXHRWarn],
json: [_toJsonString, toJsonStringWarn],
kotlin: [_toKotlin, toKotlinWarn],
matlab: [_toMATLAB, toMATLABWarn],
node: [_toNode, toNodeWarn],
"node-fetch": [_toNode, toNodeWarn], // undocumented alias
"node-axios": [_toNodeAxios, toNodeAxiosWarn],
"node-fetch": [_toNode, toNodeWarn], // undocumented alias
"node-got": [_toNodeGot, toNodeGotWarn],
"node-http": [_toNodeHttp, toNodeHttpWarn], // undocumented alias
"node-jquery": [_toJavaScriptJquery, toJavaScriptJqueryWarn], // undocumented alias
"node-request": [_toNodeRequest, toNodeRequestWarn],
"node-superagent": [_toNodeSuperAgent, toNodeSuperAgentWarn],
"node-xhr": [_toJavaScriptXHR, toJavaScriptXHRWarn], // undocumented alias
nodejs: [_toNode, toNodeWarn], // undocumented alias
"nodejs-fetch": [_toNode, toNodeWarn], // undocumented alias
"nodejs-axios": [_toNodeAxios, toNodeAxiosWarn], // undocumented alias
"nodejs-fetch": [_toNode, toNodeWarn], // undocumented alias
"nodejs-got": [_toNodeGot, toNodeGotWarn], // undocumented alias
"nodejs-http": [_toNodeHttp, toNodeHttpWarn], // undocumented alias
"nodejs-jquery": [_toJavaScriptJquery, toJavaScriptJqueryWarn], // undocumented alias
"nodejs-request": [_toNodeRequest, toNodeRequestWarn], // undocumented alias
"nodejs-superagent": [_toNodeSuperAgent, toNodeSuperAgentWarn], // undocumented alias
"nodejs-xhr": [_toJavaScriptXHR, toJavaScriptXHRWarn], // undocumented alias
php: [_toPhp, toPhpWarn],
"php-curl": [_toPhp, toPhpWarn], // undocumented alias
"php-guzzle": [_toPhpGuzzle, toPhpGuzzleWarn],
@ -140,12 +164,16 @@ language: the language to convert the curl command to. The choices are
java-httpurlconnection
java-okhttp
javascript
javascript-jquery
javascript-xhr
json
kotlin
matlab
node
node-axios
node-http
node-request
node-superagent
php
php-guzzle
php-requests

View File

@ -32,7 +32,7 @@ export interface ShortOpts {
// prettier-ignore
export const curlLongOpts = {
// BEGIN GENERATED LONG OPTIONS
// BEGIN EXTRACTED OPTIONS
"url": { type: "string", name: "url" },
"dns-ipv4-addr": { type: "string", name: "dns-ipv4-addr" },
"dns-ipv6-addr": { type: "string", name: "dns-ipv6-addr" },
@ -397,7 +397,7 @@ export const curlLongOpts = {
"progress-meter": { type: "bool", name: "progress-meter" },
"no-progress-meter": { type: "bool", name: "progress-meter", expand: false },
"next": { type: "bool", name: "next" },
// END GENERATED LONG OPTIONS
// END EXTRACTED OPTIONS
// These are options that curl used to have.
@ -534,7 +534,7 @@ export function toBoolean(opt: string): boolean {
export const curlShortOpts: {
[key: string]: keyof typeof curlLongOpts
} = {
// BEGIN GENERATED SHORT OPTIONS
// BEGIN EXTRACTED SHORT OPTIONS
"0": "http1.0",
"1": "tlsv1",
"2": "sslv2",
@ -594,7 +594,7 @@ export const curlShortOpts: {
"Z": "parallel",
"#": "progress-bar",
":": "next",
// END GENERATED SHORT OPTIONS
// END EXTRACTED SHORT OPTIONS
} as const;
export const changedShortOpts: ShortOpts = {

View File

@ -14,10 +14,9 @@ export interface Curl_URL {
// options: string /* IMAP only? */;
host: Word;
// zoneid: string /* for numerical IPv6 addresses */;
// port: string;
port: Word;
path: Word;
query: Word;
originalQuery: Word;
fragment: Word;
// portnum: number /* the numerical version */;
}
@ -109,9 +108,9 @@ export function parseurl(
const u: Curl_URL = {
scheme: new Word(),
host: new Word(),
port: new Word(),
path: new Word(), // with leading '/'
query: new Word(), // with leading '?'
originalQuery: new Word(), // with leading '?'
fragment: new Word(), // with leading '#'
};

View File

@ -1,4 +1,4 @@
import { Word, joinWords } from "../../shell/Word.js";
import { joinWords } from "../../shell/Word.js";
import { parse, getFirst, COMMON_SUPPORTED_ARGS } from "../../parse.js";
import type { Request, Warnings } from "../../parse.js";

View File

@ -265,7 +265,7 @@ export function _toNodeAxios(
}
if (request.multipartUploads) {
addImport(imports, "FormData", "form-data");
importCode += "import FormData from 'form-data';\n";
code += "const form = new FormData();\n";
for (const m of request.multipartUploads) {
code += "form.append(" + repr(m.name, imports) + ", ";

View File

@ -49,9 +49,9 @@ function getBodyString(
request: Request,
imports: JSImports
): [string | null, string | null] {
const contentType = request.headers.getContentType();
// can have things like ; charset=utf-8 which we want to preserve
const exactContentType = request.headers.get("content-type");
const contentType = request.headers.getContentType();
if (request.multipartUploads) {
if (eq(exactContentType, "multipart/form-data")) {

View File

@ -0,0 +1,237 @@
import { Word, eq, mergeWords, joinWords } from "../../shell/Word.js";
import { parse, getFirst, COMMON_SUPPORTED_ARGS } from "../../parse.js";
import type { Request, Warnings } from "../../parse.js";
import { parseQueryString } from "../../Query.js";
import {
repr,
reprObj,
asParseFloatTimes1000,
type JSImports,
reprImports,
reprAsStringToStringDict,
reprAsStringTuples,
} from "./javascript.js";
import { dedent, getFormString } from "./jquery.js";
const supportedArgs = new Set([
...COMMON_SUPPORTED_ARGS,
"form",
"form-string",
"max-time",
]);
// TODO: @
function _getDataString(
data: Word,
contentType: string | null | undefined,
imports: JSImports
): [string, string | null] {
const originalStringRepr = repr(data, imports);
if (contentType === "application/json" && data.isString()) {
const dataStr = data.toString();
const parsed = JSON.parse(dataStr);
// Only format arrays and {} as JavaScript objects
if (typeof parsed !== "object" || parsed === null) {
return [originalStringRepr, null];
}
const roundtrips = JSON.stringify(parsed) === dataStr;
const jsonAsJavaScript = "JSON.stringify(" + reprObj(parsed, 1) + ")";
return [jsonAsJavaScript, roundtrips ? null : originalStringRepr];
}
if (contentType === "application/x-www-form-urlencoded") {
const [queryList, queryDict] = parseQueryString(data);
if (queryList) {
// if (
// eq(exactContentType, "application/x-www-form-urlencoded; charset=utf-8")
// ) {
// exactContentType = null;
// }
const queryObj =
queryDict && queryDict.every((q) => !Array.isArray(q[1]))
? reprAsStringToStringDict(queryDict as [Word, Word][], 1, imports)
: reprAsStringTuples(queryList, 1, imports);
// TODO: check roundtrip, add a comment
return ["new URLSearchParams(" + queryObj + ").toString()", null];
}
}
return [originalStringRepr, null];
}
export function getDataString(
data: Word,
contentType: string | null | undefined,
imports: JSImports
): [string, string | null] {
let dataString: string | null = null;
let commentedOutDataString: string | null = null;
try {
[dataString, commentedOutDataString] = _getDataString(
data,
contentType,
imports
);
} catch {}
if (!dataString) {
dataString = repr(data, imports);
}
return [dataString, commentedOutDataString];
}
export function _toNodeHttp(
requests: Request[],
warnings: Warnings = []
): string {
const request = getFirst(requests, warnings);
const imports: JSImports = [];
let importCode = "";
let code = "";
let options = "";
const method = request.urls[0].method;
if (!eq(method, "GET")) {
options += " method: " + repr(method, imports) + ",\n";
}
if (!eq(request.urls[0].method.toUpperCase(), method)) {
warnings.push([
"method-case",
"http uppercases the method, so it will be changed to " +
JSON.stringify(method.toUpperCase().toString()),
]);
}
const url = request.urls[0].url;
let dataString, commentedOutDataString;
let formString;
const contentType = request.headers.getContentType();
if (request.data) {
[dataString, commentedOutDataString] = getDataString(
request.data,
contentType,
imports
);
} else if (request.multipartUploads) {
formString = getFormString(request.multipartUploads, imports);
code += formString;
// Node 18's native FormData doesn't have .pipe() or .getHeaders()
importCode += "import FormData from 'form-data';\n";
}
if (request.urls[0].auth) {
const [username, password] = request.urls[0].auth;
options +=
" auth: " + repr(joinWords([username, password], ":"), imports) + ",\n";
}
// TODO: warn about unsent headers
if (request.headers.length) {
options += " headers: {\n";
for (const [key, value] of request.headers) {
if (value === null) {
continue;
}
options +=
" " + repr(key, imports) + ": " + repr(value, imports) + ",\n";
}
if (formString) {
options += " ...form.getHeaders(),\n";
}
if (options.endsWith(",\n")) {
options = options.slice(0, -2);
options += "\n";
}
options += " },\n";
} else if (formString) {
options += " headers: form.getHeaders(),\n";
}
if (request.timeout) {
options +=
" timeout: " + asParseFloatTimes1000(request.timeout, imports) + ",\n";
// TODO: warn about differences from curl
}
if (options.endsWith(",\n")) {
options = options.slice(0, -2);
options += "\n";
}
const urlObj = request.urls[0].urlObj;
let optArg = repr(url, imports);
if (options) {
code += "const options = {\n";
code += " hostname: " + repr(urlObj.host, imports) + ",\n";
if (urlObj.host.includes(":")) {
// TODO
// code += " port: " + repr(request.urls[0].urlObj.port, imports) + ",\n";
warnings.push([
"node-http-port",
"Parsing the port out of the hostname is not supported. If you get an ENOTFOUND error, you'll need to do it manually",
]);
}
const path = mergeWords([urlObj.path, urlObj.query]);
if (path.toBool()) {
code += " path: " + repr(path, imports) + ",\n";
}
// code += " protocol: " + repr(urlObj.scheme, imports) + ",\n";
code += options;
code += "};\n";
code += "\n";
optArg = "options";
}
const module = urlObj.scheme.toString() === "https" ? "https" : "http";
const fn =
eq(method, "GET") && !dataString && !commentedOutDataString && !formString
? "get"
: "request";
code +=
"const req = " + module + "." + fn + "(" + optArg + ", function (res) {\n";
code += " const chunks = [];\n";
code += "\n";
code += " res.on('data', function (chunk) {\n";
code += " chunks.push(chunk);\n";
code += " });\n";
code += "\n";
code += " res.on('end', function () {\n";
code += " const body = Buffer.concat(chunks);\n";
code += " console.log(body.toString());\n";
code += " });\n";
code += "});\n";
if (commentedOutDataString) {
code += "\n// req.write(" + commentedOutDataString + ");";
}
if (dataString) {
code += "\nreq.write(" + dedent(dataString) + ");\n";
} else if (formString) {
code += "\nform.pipe(req);\n";
}
if (fn !== "get" && !formString) {
code += "req.end();\n";
}
importCode = "import " + module + " from '" + module + "';\n" + importCode;
importCode += reprImports(imports);
importCode += "\n";
return importCode + code;
}
export function toNodeHttpWarn(
curlCommand: string | string[],
warnings: Warnings = []
): [string, Warnings] {
const requests = parse(curlCommand, supportedArgs, warnings);
const code = _toNodeHttp(requests, warnings);
return [code, warnings];
}
export function toNodeHttp(curlCommand: string | string[]): string {
return toNodeHttpWarn(curlCommand)[0];
}

View File

@ -18,6 +18,33 @@ const javaScriptSupportedArgs = new Set([
const nodeSupportedArgs = new Set([...javaScriptSupportedArgs, "proxy"]);
// https://fetch.spec.whatwg.org/#forbidden-method
export const FORBIDDEN_METHODS = ["CONNECT", "TRACE", "TRACK"];
// https://fetch.spec.whatwg.org/#forbidden-request-header
export const FORBIDDEN_HEADERS = [
"Accept-Charset",
"Accept-Encoding",
"Access-Control-Request-Headers",
"Access-Control-Request-Method",
"Connection",
"Content-Length",
"Cookie",
"Cookie2",
"Date",
"DNT",
"Expect",
"Host",
"Keep-Alive",
"Origin",
"Referer",
"Set-Cookie",
"TE",
"Trailer",
"Transfer-Encoding",
"Upgrade",
"Via",
].map((h) => h.toLowerCase());
// TODO: implement?
export function reprObj(value: object, indentLevel?: number): string {
const escaped = jsescObj(value, {
@ -178,11 +205,11 @@ export function addImport(imports: JSImports, name: string, from: string) {
imports.push([name, from]);
}
export function reprImports(imports: JSImports): string {
const ret: string[] = [];
let ret = "";
for (const [name, from] of imports.sort(bySecondElem)) {
ret.push(`import { ${name} } from ${reprStr(from)};`);
ret += `import { ${name} } from ${reprStr(from)};\n`;
}
return ret.join("\n");
return ret;
}
export function reprImportsRequire(imports: JSImports): string {
const ret: string[] = [];
@ -528,6 +555,15 @@ function requestToJavaScriptOrNode(
]);
}
const method = urlObj.method.toLowerCase();
const methodStr = urlObj.method.toString();
if (method.isString() && FORBIDDEN_METHODS.includes(methodStr)) {
warnings.push([
"forbidden-method",
"the method " +
JSON.stringify(methodStr) +
" is not allowed in fetch()",
]);
}
if (
!eq(method, "get") ||
@ -562,6 +598,18 @@ function requestToJavaScriptOrNode(
": " +
reprFetch(headerValue || new Word(), isNode, imports) +
",\n";
if (
!isNode &&
headerName.isString() &&
FORBIDDEN_HEADERS.includes(headerName.toString().toLowerCase())
) {
warnings.push([
"forbidden-header",
"the header " +
JSON.stringify(headerName.toString()) +
" is not allowed in fetch()",
]);
}
}
if (urlObj.auth && request.authType === "basic") {
// TODO: if -H 'Authorization:' is passed, don't set this

View File

@ -0,0 +1,360 @@
import { Word, eq } from "../../shell/Word.js";
import { parse, getFirst, COMMON_SUPPORTED_ARGS } from "../../parse.js";
import type { Request, Warnings } from "../../parse.js";
import { parseQueryString } from "../../Query.js";
import type { Query } from "../../Query.js";
import type { FormParam } from "../../curl/form.js";
import {
repr,
reprObj,
asParseFloatTimes1000,
type JSImports,
addImport,
reprImports,
} from "./javascript.js";
const supportedArgs = new Set([
...COMMON_SUPPORTED_ARGS,
"form",
"form-string",
"max-time",
]);
export function dedent(s: string): string {
return s.replace(/^ {2}/gm, "");
}
export function indent(s: string, indent = 1): string {
const indentation = " ".repeat(indent);
return s.split("\n").join("\n" + indentation);
}
export function commentOut(s: string, indent = 0): string {
const indentation = " ".repeat(indent);
return s.split("\n").join("\n" + indentation + "// ");
}
export function serializeQuery(
query: Query,
imports: JSImports
): [string, boolean] {
const [queryList, queryDict] = query;
let code = "";
let traditional = false;
if (queryDict) {
code += "{\n";
for (const [key, value] of queryDict) {
code += " " + repr(key, imports) + ": ";
if (Array.isArray(value)) {
code += "[" + value.map((v) => repr(v, imports)).join(", ") + "]";
traditional = true;
} else {
code += repr(value, imports);
}
code += ",\n";
}
if (code.endsWith(",\n")) {
code = code.slice(0, -2);
}
code += "\n}";
} else if (queryList) {
code += "[\n";
for (const [key, value] of queryList) {
code +=
" { name: " +
repr(key, imports) +
", value: " +
repr(value, imports) +
" },\n";
}
if (code.endsWith(",\n")) {
code = code.slice(0, -2);
}
code += "\n]";
} else {
// shouldn't happen
return ["null", false];
}
return [code, traditional];
}
// TODO: @
function _getDataString(
data: Word,
contentType: string | null | undefined,
exactContentType: Word | null | undefined,
imports: JSImports
): [Word | null | undefined, string, string | null, boolean] {
let traditional = false;
const originalStringRepr = repr(data, imports);
if (contentType === "application/json" && data.isString()) {
const dataStr = data.toString();
const parsed = JSON.parse(dataStr);
// Only convert arrays and {} to JavaScript objects
if (typeof parsed !== "object" || parsed === null) {
return [exactContentType, originalStringRepr, null, traditional];
}
const roundtrips = JSON.stringify(parsed) === dataStr;
const jsonAsJavaScript = "JSON.stringify(" + reprObj(parsed, 1) + ")";
return [
exactContentType,
jsonAsJavaScript,
roundtrips ? null : originalStringRepr,
traditional,
];
}
if (contentType === "application/x-www-form-urlencoded") {
const [queryList, queryDict] = parseQueryString(data);
if (queryList) {
if (
eq(exactContentType, "application/x-www-form-urlencoded; charset=utf-8")
) {
exactContentType = null;
}
let queryObj;
[queryObj, traditional] = serializeQuery([queryList, queryDict], imports);
// TODO: check roundtrip, add a comment
return [exactContentType, indent(queryObj), null, traditional];
}
}
return [exactContentType, originalStringRepr, null, traditional];
}
export function getDataString(
data: Word,
contentType: string | null | undefined,
exactContentType: Word | null | undefined,
imports: JSImports
): [Word | null | undefined, string, string | null, boolean] {
let dataString: string | null = null;
let commentedOutDataString: string | null = null;
let traditional = false;
try {
[exactContentType, dataString, commentedOutDataString, traditional] =
_getDataString(data, contentType, exactContentType, imports);
} catch {}
if (!dataString) {
dataString = repr(data, imports);
}
return [exactContentType, dataString, commentedOutDataString, traditional];
}
export function getFormString(
multipartUploads: FormParam[],
imports: JSImports
): string {
let code = "const form = new FormData();\n";
for (const m of multipartUploads) {
code += "form.append(" + repr(m.name, imports) + ", ";
if ("contentFile" in m) {
// TODO: no fs in browser
addImport(imports, "fs", "fs");
if (eq(m.contentFile, "-")) {
code += "fs.readFileSync(0).toString()";
} else {
code += "fs.readFileSync(" + repr(m.contentFile, imports) + ")";
}
if ("filename" in m && m.filename) {
code += ", " + repr(m.filename, imports);
}
} else {
code += repr(m.content, imports);
}
code += ");\n";
}
code += "\n";
return code;
}
export function _toJavaScriptJquery(
requests: Request[],
warnings: Warnings = []
): string {
const request = getFirst(requests, warnings);
const imports: JSImports = [];
let code = "";
// data: passed with these methods will be added to the URL instead
const nonDataMethods = ["GET", "HEAD"];
const method = request.urls[0].method;
const methodStr = method.toString();
if (!eq(request.urls[0].method.toUpperCase(), method)) {
warnings.push([
"method-case",
"jQuery uppercases the method, so it will be changed to " +
JSON.stringify(method.toUpperCase().toString()),
]);
}
const contentType = request.headers.getContentType();
let exactContentType = request.headers.get("content-type");
request.headers.delete("content-type");
let url = request.urls[0].url;
let dataString: string | null = null;
let commentedOutDataString: string | null = null;
let traditional = false;
if (request.data) {
// can delete content-type header by returning null for exactContentType
[exactContentType, dataString, commentedOutDataString, traditional] =
getDataString(request.data, contentType, exactContentType, imports);
if (commentedOutDataString) {
commentedOutDataString = " // data: " + commentedOutDataString + ",\n";
}
} else if (request.multipartUploads) {
code += getFormString(request.multipartUploads, imports);
dataString = "form";
warnings.push([
"multipart-form",
// TODO: remove this when jQuery supports FormData
"jQuery doesn't support sending FormData yet",
]);
}
if (nonDataMethods.includes(methodStr)) {
if (request.urls[0].queryList) {
if (dataString) {
warnings.push([
"data-with-get",
"jQuery doesn't allow sending data in the body with GET or HEAD requests",
]);
if (commentedOutDataString) {
commentedOutDataString +=
" // data: " + indent(commentOut(dedent(dataString))) + ",\n";
} else {
commentedOutDataString =
" // data: " + indent(commentOut(dedent(dataString))) + ",\n";
}
}
[dataString, traditional] = serializeQuery(
[request.urls[0].queryList, request.urls[0].queryDict ?? null],
imports
);
dataString = indent(dataString);
url = request.urls[0].urlWithoutQueryList;
} else if (request.data || request.multipartUploads) {
warnings.push([
"data-with-get",
"jQuery doesn't allow sending data with GET or HEAD requests. The data will be sent in the URL instead",
]);
}
}
const needsConfig = !!(
request.headers.length ||
request.urls[0].auth ||
((request.multipartUploads || request.data) &&
nonDataMethods.includes(methodStr)) ||
request.timeout ||
(exactContentType !== null && exactContentType !== undefined) ||
commentedOutDataString ||
traditional
);
let done = "";
done += ".done(function(response) {\n";
done += " console.log(response);\n";
done += "});";
if (
!needsConfig &&
method.isString() &&
["GET", "POST"].includes(methodStr)
) {
// TODO: .getJSON()
const fn = methodStr === "GET" ? "get" : "post";
code += "$." + fn + "(";
code += repr(url, imports);
if (dataString) {
code += ", " + dedent(dataString);
}
code += ")\n";
code += " " + indent(done) + "\n";
} else {
code += "$.ajax({\n";
code += " url: " + repr(url, imports) + ",\n";
code += " crossDomain: true,\n";
if (methodStr !== "GET") {
// jQuery uppercases methods
const sentMethod = eq(request.urls[0].method.toUpperCase(), method)
? method.toLowerCase()
: method;
code += " method: " + repr(sentMethod, imports) + ",\n";
}
if (request.headers.length) {
code += " headers: {\n";
for (const [key, value] of request.headers) {
if (value === null) {
continue;
}
code +=
" " + repr(key, imports) + ": " + repr(value, imports) + ",\n";
}
if (code.endsWith(",\n")) {
code = code.slice(0, -2);
code += "\n";
}
code += " },\n";
}
if (exactContentType) {
code += " contentType: " + repr(exactContentType, imports) + ",\n";
}
if (request.urls[0].auth) {
const [username, password] = request.urls[0].auth;
code += " username: " + repr(username, imports) + ",\n";
code += " password: " + repr(password, imports) + ",\n";
}
if (commentedOutDataString) {
code += commentedOutDataString;
}
if (dataString) {
code += " data: " + dataString + ",\n";
}
if (traditional) {
code += " traditional: true,\n";
}
if (request.timeout) {
code +=
" timeout: " + asParseFloatTimes1000(request.timeout, imports) + ",\n";
}
if (code.endsWith(",\n")) {
code = code.slice(0, -2);
code += "\n";
}
code += "})" + done + "\n";
}
let importCode = reprImports(imports);
if (importCode) {
importCode += "\n";
}
return importCode + code;
}
export function toJavaScriptJqueryWarn(
curlCommand: string | string[],
warnings: Warnings = []
): [string, Warnings] {
const requests = parse(curlCommand, supportedArgs, warnings);
const jquery = _toJavaScriptJquery(requests, warnings);
return [jquery, warnings];
}
export function toJavaScriptJquery(curlCommand: string | string[]): string {
return toJavaScriptJqueryWarn(curlCommand)[0];
}

View File

@ -0,0 +1,370 @@
import { Word, eq } from "../../shell/Word.js";
import { parse, getFirst, COMMON_SUPPORTED_ARGS } from "../../parse.js";
import type { Request, Warnings } from "../../parse.js";
import { parseQueryString } from "../../Query.js";
import type { Query } from "../../Query.js";
import type { FormParam } from "../../curl/form.js";
import {
repr,
reprObj,
asParseFloatTimes1000,
type JSImports,
addImport,
reprImports,
} from "./javascript.js";
import { indent } from "./jquery.js";
const supportedArgs = new Set([
...COMMON_SUPPORTED_ARGS,
"form",
"form-string",
"max-time",
"connect-timeout",
"location", // --no-location only has an effect
"max-redirs",
"insecure",
"cert",
"key",
"cacert",
"http2",
]);
function serializeQuery(
fn: "query" | "send",
query: Query,
imports: JSImports
): string {
const [queryList, queryDict] = query;
let code = "";
if (queryDict) {
code += "{\n";
for (const [key, value] of queryDict) {
code += " " + repr(key, imports) + ": ";
if (Array.isArray(value)) {
code += "[" + value.map((v) => repr(v, imports)).join(", ") + "]";
} else {
code += repr(value, imports);
}
code += ",\n";
}
if (code.endsWith(",\n")) {
code = code.slice(0, -2);
}
code += "\n}";
code = " ." + fn + "(" + indent(code) + ")\n";
} else if (queryList) {
for (const [key, value] of queryList) {
code +=
" ." +
fn +
"({ " +
repr(key, imports) +
": " +
repr(value, imports) +
" })\n";
}
} else {
// shouldn't happen
return "";
}
return code;
}
// TODO: @
function _getDataString(
request: Request,
contentType: string | null | undefined,
exactContentType: Word | null | undefined,
imports: JSImports
): [Word | null | undefined, string | null, string | null] {
if (!request.data) {
return [exactContentType, null, null];
}
const originalStringRepr = " .send(" + repr(request.data, imports) + ")\n";
if (contentType === "application/json" && request.data.isString()) {
const dataStr = request.data.toString();
const parsed = JSON.parse(dataStr);
// Only convert arrays and {} to JavaScript objects
if (typeof parsed !== "object" || parsed === null) {
return [exactContentType, originalStringRepr, null];
}
const roundtrips = JSON.stringify(parsed) === dataStr;
const jsonAsJavaScript = " .send(" + reprObj(parsed, 1) + ")\n";
if (roundtrips && eq(exactContentType, "application/json")) {
exactContentType = null;
}
return [
exactContentType,
jsonAsJavaScript,
roundtrips ? null : originalStringRepr,
];
}
if (contentType === "application/x-www-form-urlencoded") {
const [queryList, queryDict] = parseQueryString(request.data);
if (queryList) {
exactContentType = null;
const queryCode =
" .type('form')\n" +
serializeQuery("send", [queryList, queryDict], imports);
// TODO: check roundtrip, add a comment
return [exactContentType, queryCode, null];
}
}
return [exactContentType, originalStringRepr, null];
}
export function getDataString(
request: Request,
contentType: string | null | undefined,
exactContentType: Word | null | undefined,
imports: JSImports
): [Word | null | undefined, string | null, string | null] {
if (!request.data) {
return [exactContentType, null, null];
}
let dataString: string | null = null;
let commentedOutDataString: string | null = null;
try {
[exactContentType, dataString, commentedOutDataString] = _getDataString(
request,
contentType,
exactContentType,
imports
);
} catch {}
if (!dataString) {
dataString = " .send(" + repr(request.data, imports) + ")\n";
}
return [exactContentType, dataString, commentedOutDataString];
}
export function getFormString(
multipartUploads: FormParam[],
imports: JSImports
): string {
let code = "";
for (const m of multipartUploads) {
if ("contentFile" in m) {
code += " .attach(" + repr(m.name, imports);
// if (eq(m.contentFile, "-")) {
// warnings.push([
// "stdin-file", "SuperAgent doesn't support reading from stdin",
// ]);
// }
code += ", " + repr(m.contentFile, imports);
if ("filename" in m && m.filename) {
code += ", " + repr(m.filename, imports);
}
code += ")\n";
} else {
code +=
" .field(" +
repr(m.name, imports) +
", " +
repr(m.content, imports) +
")\n";
}
}
return code;
}
export function _toNodeSuperAgent(
requests: Request[],
warnings: Warnings = []
): string {
const request = getFirst(requests, warnings);
const imports: JSImports = [];
let code = "";
// data: passed with these methods is ignored
const method = request.urls[0].method;
const methodStr = method.toString();
// https://github.com/ladjs/superagent/blob/73c7efb5e9a0cf0409da9918d49b89055be29db5/src/client.js#L899
const nonDataMethods = ["GET", "HEAD"];
if (!eq(request.urls[0].method.toUpperCase(), method)) {
warnings.push([
"method-case",
"SuperAgent uppercases the method, so it will be changed to " +
JSON.stringify(method.toUpperCase().toString()),
]);
}
const hasData = request.data || request.multipartUploads;
const url = request.urls[0].queryList
? request.urls[0].urlWithoutQueryList
: request.urls[0].url;
const contentType = request.headers.getContentType();
let exactContentType = request.headers.get("content-type");
request.headers.delete("content-type");
let dataCode, commentedOutDataCode;
if (request.data) {
// might delete content-type header
[exactContentType, dataCode, commentedOutDataCode] = getDataString(
request,
contentType,
exactContentType,
imports
);
} else if (request.multipartUploads) {
dataCode = getFormString(request.multipartUploads, imports);
exactContentType = null;
}
if (nonDataMethods.includes(methodStr) && hasData) {
warnings.push([
"data-with-get",
"SuperAgent doesn't send data with GET or HEAD requests",
]);
}
// https://github.com/ladjs/superagent/blob/73c7efb5e9a0cf0409da9918d49b89055be29db5/src/client.js#L899
const methodToFn = {
GET: "get",
HEAD: "head",
OPTIONS: "options",
DELETE: "del",
PATCH: "patch",
POST: "post",
PUT: "put",
} as const;
code += "request";
if (methodStr in methodToFn) {
const fn = methodToFn[methodStr as keyof typeof methodToFn];
code += "\n";
code += " ." + fn + "(" + repr(url, imports) + ")\n";
} else {
code += "(" + repr(method, imports) + ", " + repr(url, imports) + ")\n";
}
if (request.urls[0].queryList) {
code += serializeQuery(
"query",
[request.urls[0].queryList, request.urls[0].queryDict ?? null],
imports
);
}
if (request.urls[0].auth) {
const [username, password] = request.urls[0].auth;
code +=
" .auth(" +
repr(username, imports) +
", " +
repr(password, imports) +
")\n";
}
// TODO: warn about unsent headers
if (request.headers.length) {
for (const [key, value] of request.headers) {
if (value === null) {
continue;
}
code +=
" .set(" + repr(key, imports) + ", " + repr(value, imports) + ")\n";
}
}
if (exactContentType) {
if (eq(exactContentType, "application/x-www-form-urlencoded")) {
code += " .type('form')\n";
} else if (eq(exactContentType, "application/json")) {
code += " .type('json')\n";
} else {
code += " .type(" + repr(exactContentType, imports) + ")\n";
}
}
if (commentedOutDataCode) {
code += " //" + commentedOutDataCode;
}
if (dataCode) {
code += dataCode;
}
if (request.connectTimeout) {
code += " .timeout({ ";
code +=
"response: " + asParseFloatTimes1000(request.connectTimeout, imports);
if (request.timeout) {
code += "deadline: " + asParseFloatTimes1000(request.timeout, imports);
}
code += " })\n";
} else if (request.timeout) {
code +=
" .timeout(" + asParseFloatTimes1000(request.timeout, imports) + ")\n";
}
if (request.followRedirects === false) {
code += " .redirects(0)\n";
} else if (request.maxRedirects) {
code += " .redirects(" + repr(request.maxRedirects, imports) + ")\n";
}
// TODO
// if (request.retry) {
// code += " .retry(" + request.retry.toString() + ")\n";
// }
if (request.insecure) {
code += " .disableTLSCerts()\n";
}
if (request.cert) {
const [cert, password] = request.cert;
code += " .cert(fs.readFileSync(" + repr(cert, imports) + "))\n";
addImport(imports, "fs", "fs");
if (password) {
warnings.push([
"cert-password",
"SuperAgent doesn't support certificate passwords: " +
JSON.stringify(password.toString()),
]);
}
}
if (request.key) {
code += " .key(fs.readFileSync(" + repr(request.key, imports) + "))\n";
addImport(imports, "fs", "fs");
}
// TODO: is this correct?
if (request.cacert) {
code += " .ca(fs.readFileSync(" + repr(request.cacert, imports) + "))\n";
addImport(imports, "fs", "fs");
}
if (request.http2) {
code += " .http2()\n";
}
code += " .then(res => {\n";
code += " console.log(res.body);\n";
code += " });\n";
let importCode = "import request from 'superagent';\n";
importCode += reprImports(imports);
importCode += "\n";
return importCode + code;
}
export function toNodeSuperAgentWarn(
curlCommand: string | string[],
warnings: Warnings = []
): [string, Warnings] {
const requests = parse(curlCommand, supportedArgs, warnings);
const code = _toNodeSuperAgent(requests, warnings);
return [code, warnings];
}
export function toNodeSuperAgent(curlCommand: string | string[]): string {
return toNodeSuperAgentWarn(curlCommand)[0];
}

View File

@ -0,0 +1,197 @@
import { Word, eq } from "../../shell/Word.js";
import { parse, getFirst, COMMON_SUPPORTED_ARGS } from "../../parse.js";
import type { Request, Warnings } from "../../parse.js";
import { parseQueryString } from "../../Query.js";
import {
repr,
reprObj,
asParseFloatTimes1000,
type JSImports,
reprImports,
reprAsStringToStringDict,
reprAsStringTuples,
} from "./javascript.js";
import { dedent, getFormString } from "./jquery.js";
const supportedArgs = new Set([
...COMMON_SUPPORTED_ARGS,
"form",
"form-string",
"max-time",
]);
function _getDataString(
data: Word,
contentType: string | null | undefined,
imports: JSImports
): [string, string | null] {
const originalStringRepr = repr(data, imports);
if (contentType === "application/json" && data.isString()) {
const dataStr = data.toString();
const parsed = JSON.parse(dataStr);
// Only convert arrays and {} to JS objects
if (typeof parsed !== "object" || parsed === null) {
return [originalStringRepr, null];
}
const roundtrips = JSON.stringify(parsed) === dataStr;
const jsonAsJavaScript = "JSON.stringify(" + reprObj(parsed, 1) + ")";
return [jsonAsJavaScript, roundtrips ? null : originalStringRepr];
}
if (contentType === "application/x-www-form-urlencoded") {
const [queryList, queryDict] = parseQueryString(data);
if (queryList) {
const queryObj =
queryDict && queryDict.every((q) => !Array.isArray(q[1]))
? reprAsStringToStringDict(queryDict as [Word, Word][], 1, imports)
: reprAsStringTuples(queryList, 1, imports);
// TODO: check roundtrip, add a comment
return ["new URLSearchParams(" + queryObj + ")", null];
}
}
return [originalStringRepr, null];
}
export function getDataString(
data: Word,
contentType: string | null | undefined,
imports: JSImports
): [string, string | null] {
let dataString: string | null = null;
let commentedOutDataString: string | null = null;
try {
[dataString, commentedOutDataString] = _getDataString(
data,
contentType,
imports
);
} catch {}
if (!dataString) {
dataString = repr(data, imports);
}
return [dataString, commentedOutDataString];
}
export function _toJavaScriptXHR(
requests: Request[],
warnings: Warnings = []
): string {
const request = getFirst(requests, warnings);
const imports: JSImports = [];
let code = "";
// data: passed with these methods is ignored
const nonDataMethods = ["GET", "HEAD"];
const method = request.urls[0].method;
const methodStr = method.toString();
if (!eq(request.urls[0].method.toUpperCase(), method)) {
warnings.push([
"method-case",
"XHR uppercases the method, so it will be changed to " +
JSON.stringify(method.toUpperCase().toString()),
]);
}
const hasData = request.data || request.multipartUploads;
const url = request.urls[0].url;
const contentType = request.headers.getContentType();
if (request.data) {
// might delete content-type header
const [dataString, commentedOutDataString] = getDataString(
request.data,
contentType,
imports
);
if (commentedOutDataString) {
code += "// const data = " + commentedOutDataString + ";\n";
}
if (dataString) {
code += "const data = " + dedent(dataString) + ";\n\n";
}
} else if (request.multipartUploads) {
code += getFormString(request.multipartUploads, imports);
}
if (nonDataMethods.includes(methodStr) && hasData) {
warnings.push([
"data-with-get",
"XHR doesn't send data with GET or HEAD requests",
]);
}
code += "let xhr = new XMLHttpRequest();\n";
code += "xhr.withCredentials = true;\n";
code += "xhr.open(";
const openArgs = [repr(method, imports), repr(url, imports)];
if (request.urls[0].auth) {
const [username, password] = request.urls[0].auth;
openArgs.push("true", repr(username, imports), repr(password, imports));
code += "\n ";
code += openArgs.join(",\n ");
code += "\n";
} else {
code += openArgs.join(", ");
}
code += ");\n";
// TODO: keep content-type header if it's not multipart/form-data
// TODO: warn about unsent headers
if (request.headers.length) {
for (const [key, value] of request.headers) {
if (value === null) {
continue;
}
code +=
"xhr.setRequestHeader(" +
repr(key, imports) +
", " +
repr(value, imports) +
");\n";
}
}
if (request.timeout) {
code +=
"xhr.timeout = " +
asParseFloatTimes1000(request.timeout, imports) +
";\n";
}
code += "\n";
code += "xhr.onload = function() {\n";
code += " console.log(xhr.response);\n";
code += "};\n";
code += "\n";
if (request.data) {
code += "xhr.send(data);\n";
} else if (request.multipartUploads) {
code += "xhr.send(form);\n";
} else {
code += "xhr.send();\n";
}
let importCode = reprImports(imports);
if (importCode) {
importCode += "\n";
}
return importCode + code;
}
export function toJavaScriptXHRWarn(
curlCommand: string | string[],
warnings: Warnings = []
): [string, Warnings] {
const requests = parse(curlCommand, supportedArgs, warnings);
const code = _toJavaScriptXHR(requests, warnings);
return [code, warnings];
}
export function toJavaScriptXHR(curlCommand: string | string[]): string {
return toJavaScriptXHRWarn(curlCommand)[0];
}

View File

@ -1,12 +1,6 @@
export { toAnsible, toAnsibleWarn } from "./generators/ansible.js";
export { toCFML, toCFMLWarn } from "./generators/cfml.js";
export { toClojure, toClojureWarn } from "./generators/clojure.js";
export {
toJavaScript,
toJavaScriptWarn,
} from "./generators/javascript/javascript.js";
export { toNodeAxios, toNodeAxiosWarn } from "./generators/javascript/axios.js";
export { toNodeGot, toNodeGotWarn } from "./generators/javascript/got.js";
export { toCSharp, toCSharpWarn } from "./generators/csharp.js";
export { toDart, toDartWarn } from "./generators/dart.js";
export { toElixir, toElixirWarn } from "./generators/elixir.js";
@ -20,10 +14,29 @@ export {
toJavaHttpUrlConnectionWarn,
} from "./generators/java/httpurlconnection.js";
export { toJavaOkHttp, toJavaOkHttpWarn } from "./generators/java/okhttp.js";
export {
toJavaScript,
toJavaScriptWarn,
} from "./generators/javascript/javascript.js";
export {
toJavaScriptJquery,
toJavaScriptJqueryWarn,
} from "./generators/javascript/jquery.js";
export {
toJavaScriptXHR,
toJavaScriptXHRWarn,
} from "./generators/javascript/xhr.js";
export { toJsonString, toJsonStringWarn } from "./generators/json.js";
export { toKotlin, toKotlinWarn } from "./generators/kotlin.js";
export { toMATLAB, toMATLABWarn } from "./generators/matlab/matlab.js";
export { toNode, toNodeWarn } from "./generators/javascript/javascript.js";
export { toNodeAxios, toNodeAxiosWarn } from "./generators/javascript/axios.js";
export { toNodeGot, toNodeGotWarn } from "./generators/javascript/got.js";
export { toNodeHttp, toNodeHttpWarn } from "./generators/javascript/http.js";
export {
toNodeSuperAgent,
toNodeSuperAgentWarn,
} from "./generators/javascript/superagent.js";
export {
toNodeRequest,
toNodeRequestWarn,

View File

@ -0,0 +1,13 @@
$.ajax({
url: 'http://localhost:28139',
crossDomain: true,
method: 'post',
headers: {
'Accept': 'application/json'
},
contentType: 'application/json',
// data: '{ }',
data: JSON.stringify({})
}).done(function(response) {
console.log(response);
});

8
test/fixtures/javascript-jquery/get_basic_auth.js generated vendored Normal file
View File

@ -0,0 +1,8 @@
$.ajax({
url: 'http://localhost:28139/',
crossDomain: true,
username: 'some_username',
password: 'some_password'
}).done(function(response) {
console.log(response);
});

View File

@ -0,0 +1,49 @@
$.ajax({
url: 'http://localhost:28139/house-sitting/',
crossDomain: true,
data: {
'page': '1',
'available': ['', '1'],
'location': '0',
'city[id]': '0',
'city[locality]': '',
'city[locality_text]': '',
'city[administrative_area_level_2]': '',
'city[administrative_area_level_2_text]': '',
'city[administrative_area_level_1]': '',
'city[administrative_area_level_1_text]': '',
'city[country]': '',
'city[country_text]': '',
'city[latitude]': '',
'city[longitude]': '',
'city[zoom]': '',
'city[name]': '',
'region[id]': '0',
'region[locality]': '',
'region[locality_text]': '',
'region[administrative_area_level_2]': '',
'region[administrative_area_level_2_text]': '',
'region[administrative_area_level_1]': '',
'region[administrative_area_level_1_text]': '',
'region[country]': '',
'region[country_text]': '',
'region[latitude]': '',
'region[longitude]': '',
'region[zoom]': '',
'region[name]': '',
'country': '',
'environment': '',
'population': '',
'period': '0',
'date': '2017-03-03',
'datestart': '2017-03-03',
'dateend': '2017-06-24',
'season': '',
'duration': '',
'isfd': '',
'stopover': ''
},
traditional: true
}).done(function(response) {
console.log(response);
});

7
test/fixtures/javascript-jquery/get_max_time.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
$.ajax({
url: 'http://localhost:28139',
crossDomain: true,
timeout: 20000
}).done(function(response) {
console.log(response);
});

11
test/fixtures/javascript-jquery/get_referer.js generated vendored Normal file
View File

@ -0,0 +1,11 @@
$.ajax({
url: 'http://localhost:28139',
crossDomain: true,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'SimCity',
'Referer': 'https://website.com'
}
}).done(function(response) {
console.log(response);
});

View File

@ -0,0 +1,12 @@
$.ajax({
url: 'http://localhost:28139/CurlToNode',
crossDomain: true,
method: 'post',
headers: {
'Accept': 'application/json'
},
contentType: 'application/json',
data: '18233982904'
}).done(function(response) {
console.log(response);
});

View File

@ -0,0 +1,15 @@
$.ajax({
url: 'http://localhost:28139/',
crossDomain: true,
headers: {
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Referer': 'http://www.wikipedia.org/',
'Cookie': 'GeoIP=US:Albuquerque:35.1241:-106.7675:v4; uls-previous-languages=%5B%22en%22%5D; mediaWiki.user.sessionId=VaHaeVW3m0ymvx9kacwshZIDkv8zgF9y; centralnotice_buckets_by_campaign=%7B%22C14_enUS_dsk_lw_FR%22%3A%7B%22val%22%3A%220%22%2C%22start%22%3A1412172000%2C%22end%22%3A1422576000%7D%2C%22C14_en5C_dec_dsk_FR%22%3A%7B%22val%22%3A3%2C%22start%22%3A1417514400%2C%22end%22%3A1425290400%7D%2C%22C14_en5C_bkup_dsk_FR%22%3A%7B%22val%22%3A1%2C%22start%22%3A1417428000%2C%22end%22%3A1425290400%7D%7D; centralnotice_bannercount_fr12=22; centralnotice_bannercount_fr12-wait=14',
'Connection': 'keep-alive'
}
}).done(function(response) {
console.log(response);
});

14
test/fixtures/javascript-jquery/get_with_data.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
$.ajax({
url: 'http://localhost:28139/synthetics/api/v3/monitors',
crossDomain: true,
headers: {
'X-Api-Key': '123456789'
},
data: {
'test': '2',
'limit': '100',
'w': '4'
}
}).done(function(response) {
console.log(response);
});

11
test/fixtures/javascript-jquery/get_with_data2.js generated vendored Normal file
View File

@ -0,0 +1,11 @@
$.ajax({
url: 'http://localhost:28139/v2/alerts_policy_channels.json?policy_id=policy_id&channel_ids=channel_id',
crossDomain: true,
method: 'put',
headers: {
'X-Api-Key': '{admin_api_key}'
},
contentType: 'application/json'
}).done(function(response) {
console.log(response);
});

13
test/fixtures/javascript-jquery/get_with_env_var.js generated vendored Normal file
View File

@ -0,0 +1,13 @@
$.ajax({
url: 'http://localhost:28139/v2/images',
crossDomain: true,
headers: {
'Authorization': 'Bearer ' + process.env['DO_API_TOKEN']
},
contentType: 'application/json',
data: {
'type': 'distribution'
}
}).done(function(response) {
console.log(response);
});

16
test/fixtures/javascript-jquery/get_with_form.js generated vendored Normal file
View File

@ -0,0 +1,16 @@
const form = new FormData();
form.append('from', 'test@tester.com');
form.append('to', 'devs@tester.net');
form.append('subject', 'Hello');
form.append('text', 'Testing the converter!');
$.ajax({
url: 'http://localhost:28139/v3',
crossDomain: true,
method: 'post',
username: 'test',
password: '',
data: form
}).done(function(response) {
console.log(response);
});

View File

@ -0,0 +1,14 @@
$.ajax({
url: 'http://localhost:28139/echo/html/',
crossDomain: true,
headers: {
'Origin': 'http://fiddle.jshell.net'
},
contentType: 'application/x-www-form-urlencoded',
data: {
'msg1': 'value1',
'msg2': 'value2'
}
}).done(function(response) {
console.log(response);
});

17
test/fixtures/javascript-jquery/multipart_post.js generated vendored Normal file
View File

@ -0,0 +1,17 @@
import { fs } from 'fs';
const form = new FormData();
form.append('attributes', '{"name":"tigers.jpeg", "parent":{"id":"11446498"}}');
form.append('file', fs.readFileSync('myfile.jpg'), 'myfile.jpg');
$.ajax({
url: 'http://localhost:28139/api/2.0/files/content',
crossDomain: true,
method: 'post',
headers: {
'Authorization': 'Bearer ACCESS_TOKEN'
},
data: form
}).done(function(response) {
console.log(response);
});

9
test/fixtures/javascript-jquery/post_empty.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
$.ajax({
url: 'http://localhost:28139',
crossDomain: true,
method: 'post',
contentType: 'application/x-www-form-urlencoded',
data: ''
}).done(function(response) {
console.log(response);
});

View File

@ -0,0 +1,9 @@
$.ajax({
url: 'http://localhost:28139/post',
crossDomain: true,
method: 'post',
contentType: 'application/x-www-form-urlencoded',
data: 'secret=*%5*!'
}).done(function(response) {
console.log(response);
});

View File

@ -0,0 +1,22 @@
$.ajax({
url: 'http://localhost:28139/echo/html/',
crossDomain: true,
method: 'post',
headers: {
'Origin': 'http://fiddle.jshell.net',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
'Accept': '*/*',
'Referer': 'http://fiddle.jshell.net/_display/',
'X-Requested-With': 'XMLHttpRequest',
'Connection': 'keep-alive'
},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: {
'msg1': 'wow',
'msg2': 'such'
}
}).done(function(response) {
console.log(response);
});

View File

@ -0,0 +1,40 @@
$.ajax({
url: 'http://localhost:28139/api/Listing.svc/PropertySearch_Post',
crossDomain: true,
method: 'post',
headers: {
'Origin': 'http://www.realtor.ca',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
'Accept': '*/*',
'Referer': 'http://www.realtor.ca/Residential/Map.aspx',
'Connection': 'keep-alive'
},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: {
'CultureId': '1',
'ApplicationId': '1',
'RecordsPerPage': '200',
'MaximumResults': '200',
'PropertyTypeId': '300',
'TransactionTypeId': '2',
'StoreyRange': '0-0',
'BuildingTypeId': '1',
'BedRange': '0-0',
'BathRange': '0-0',
'LongitudeMin': '-79.3676805496215',
'LongitudeMax': '-79.27300930023185',
'LatitudeMin': '43.660358732823845',
'LatitudeMax': '43.692390574029936',
'SortOrder': 'A',
'SortBy': '1',
'viewState': 'm',
'Longitude': '-79.4107246398925',
'Latitude': '43.6552047278685',
'ZoomLevel': '13',
'CurrentPage': '1'
}
}).done(function(response) {
console.log(response);
});

9
test/fixtures/javascript-jquery/post_xpost.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
$.ajax({
url: 'http://localhost:28139/api/xxxxxxxxxxxxxxxx',
crossDomain: true,
method: 'post',
contentType: 'application/x-www-form-urlencoded',
data: '{"keywords":"php","page":1,"searchMode":1}'
}).done(function(response) {
console.log(response);
});

10
test/fixtures/javascript-jquery/repeated_query_key.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
$.ajax({
url: 'http://localhost:28139',
crossDomain: true,
data: {
'key': ['one', 'two']
},
traditional: true
}).done(function(response) {
console.log(response);
});

View File

@ -0,0 +1,7 @@
$.ajax({
url: 'http://localhost:28139',
crossDomain: true,
method: 'wHat'
}).done(function(response) {
console.log(response);
});

7
test/fixtures/javascript-jquery/url_query.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
$.get('http://localhost:28139', {
'foo': 'bar',
'baz': 'qux'
})
.done(function(response) {
console.log(response);
});

View File

@ -0,0 +1,14 @@
// const data = '{ }';
const data = JSON.stringify({});
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'http://localhost:28139');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Accept', 'application/json');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send(data);

15
test/fixtures/javascript-xhr/get_basic_auth.js generated vendored Normal file
View File

@ -0,0 +1,15 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open(
'GET',
'http://localhost:28139/',
true,
'some_username',
'some_password'
);
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

View File

@ -0,0 +1,9 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', 'http://localhost:28139/house-sitting/?page=1&available=&available=1&location=0&city%5Bid%5D=0&city%5Blocality%5D=&city%5Blocality_text%5D=&city%5Badministrative_area_level_2%5D=&city%5Badministrative_area_level_2_text%5D=&city%5Badministrative_area_level_1%5D=&city%5Badministrative_area_level_1_text%5D=&city%5Bcountry%5D=&city%5Bcountry_text%5D=&city%5Blatitude%5D=&city%5Blongitude%5D=&city%5Bzoom%5D=&city%5Bname%5D=&region%5Bid%5D=0&region%5Blocality%5D=&region%5Blocality_text%5D=&region%5Badministrative_area_level_2%5D=&region%5Badministrative_area_level_2_text%5D=&region%5Badministrative_area_level_1%5D=&region%5Badministrative_area_level_1_text%5D=&region%5Bcountry%5D=&region%5Bcountry_text%5D=&region%5Blatitude%5D=&region%5Blongitude%5D=&region%5Bzoom%5D=&region%5Bname%5D=&country=&environment=&population=&period=0&date=2017-03-03&datestart=2017-03-03&dateend=2017-06-24&season=&duration=&isfd=&stopover=');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

10
test/fixtures/javascript-xhr/get_max_time.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', 'http://localhost:28139');
xhr.timeout = 20000;
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

View File

@ -0,0 +1,13 @@
const data = '18233982904';
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'http://localhost:28139/CurlToNode');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Accept', 'application/json');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send(data);

View File

@ -0,0 +1,16 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', 'http://localhost:28139/');
xhr.setRequestHeader('Accept-Encoding', 'gzip, deflate, sdch');
xhr.setRequestHeader('Accept-Language', 'en-US,en;q=0.8');
xhr.setRequestHeader('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36');
xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8');
xhr.setRequestHeader('Referer', 'http://www.wikipedia.org/');
xhr.setRequestHeader('Cookie', 'GeoIP=US:Albuquerque:35.1241:-106.7675:v4; uls-previous-languages=%5B%22en%22%5D; mediaWiki.user.sessionId=VaHaeVW3m0ymvx9kacwshZIDkv8zgF9y; centralnotice_buckets_by_campaign=%7B%22C14_enUS_dsk_lw_FR%22%3A%7B%22val%22%3A%220%22%2C%22start%22%3A1412172000%2C%22end%22%3A1422576000%7D%2C%22C14_en5C_dec_dsk_FR%22%3A%7B%22val%22%3A3%2C%22start%22%3A1417514400%2C%22end%22%3A1425290400%7D%2C%22C14_en5C_bkup_dsk_FR%22%3A%7B%22val%22%3A1%2C%22start%22%3A1417428000%2C%22end%22%3A1425290400%7D%7D; centralnotice_bannercount_fr12=22; centralnotice_bannercount_fr12-wait=14');
xhr.setRequestHeader('Connection', 'keep-alive');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

10
test/fixtures/javascript-xhr/get_with_data.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', 'http://localhost:28139/synthetics/api/v3/monitors?test=2&limit=100&w=4');
xhr.setRequestHeader('X-Api-Key', '123456789');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

11
test/fixtures/javascript-xhr/get_with_data2.js generated vendored Normal file
View File

@ -0,0 +1,11 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('PUT', 'http://localhost:28139/v2/alerts_policy_channels.json?policy_id=policy_id&channel_ids=channel_id');
xhr.setRequestHeader('X-Api-Key', '{admin_api_key}');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

11
test/fixtures/javascript-xhr/get_with_env_var.js generated vendored Normal file
View File

@ -0,0 +1,11 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', 'http://localhost:28139/v2/images?type=distribution');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer ' + process.env['DO_API_TOKEN']);
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

21
test/fixtures/javascript-xhr/get_with_form.js generated vendored Normal file
View File

@ -0,0 +1,21 @@
const form = new FormData();
form.append('from', 'test@tester.com');
form.append('to', 'devs@tester.net');
form.append('subject', 'Hello');
form.append('text', 'Testing the converter!');
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open(
'POST',
'http://localhost:28139/v3',
true,
'test',
''
);
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send(form);

View File

@ -0,0 +1,16 @@
const data = new URLSearchParams({
'msg1': 'value1',
'msg2': 'value2'
});
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', 'http://localhost:28139/echo/html/');
xhr.setRequestHeader('Origin', 'http://fiddle.jshell.net');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send(data);

16
test/fixtures/javascript-xhr/multipart_post.js generated vendored Normal file
View File

@ -0,0 +1,16 @@
import { fs } from 'fs';
const form = new FormData();
form.append('attributes', '{"name":"tigers.jpeg", "parent":{"id":"11446498"}}');
form.append('file', fs.readFileSync('myfile.jpg'), 'myfile.jpg');
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'http://localhost:28139/api/2.0/files/content');
xhr.setRequestHeader('Authorization', 'Bearer ACCESS_TOKEN');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send(form);

12
test/fixtures/javascript-xhr/post_empty.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
const data = '';
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'http://localhost:28139');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send(data);

View File

@ -0,0 +1,12 @@
const data = 'secret=*%5*!';
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'http://localhost:28139/post');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send(data);

View File

@ -0,0 +1,23 @@
const data = new URLSearchParams({
'msg1': 'wow',
'msg2': 'such'
});
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'http://localhost:28139/echo/html/');
xhr.setRequestHeader('Origin', 'http://fiddle.jshell.net');
xhr.setRequestHeader('Accept-Encoding', 'gzip, deflate');
xhr.setRequestHeader('Accept-Language', 'en-US,en;q=0.8');
xhr.setRequestHeader('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.setRequestHeader('Accept', '*/*');
xhr.setRequestHeader('Referer', 'http://fiddle.jshell.net/_display/');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Connection', 'keep-alive');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send(data);

View File

@ -0,0 +1,41 @@
const data = new URLSearchParams({
'CultureId': '1',
'ApplicationId': '1',
'RecordsPerPage': '200',
'MaximumResults': '200',
'PropertyTypeId': '300',
'TransactionTypeId': '2',
'StoreyRange': '0-0',
'BuildingTypeId': '1',
'BedRange': '0-0',
'BathRange': '0-0',
'LongitudeMin': '-79.3676805496215',
'LongitudeMax': '-79.27300930023185',
'LatitudeMin': '43.660358732823845',
'LatitudeMax': '43.692390574029936',
'SortOrder': 'A',
'SortBy': '1',
'viewState': 'm',
'Longitude': '-79.4107246398925',
'Latitude': '43.6552047278685',
'ZoomLevel': '13',
'CurrentPage': '1'
});
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'http://localhost:28139/api/Listing.svc/PropertySearch_Post');
xhr.setRequestHeader('Origin', 'http://www.realtor.ca');
xhr.setRequestHeader('Accept-Encoding', 'gzip, deflate');
xhr.setRequestHeader('Accept-Language', 'en-US,en;q=0.8');
xhr.setRequestHeader('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.setRequestHeader('Accept', '*/*');
xhr.setRequestHeader('Referer', 'http://www.realtor.ca/Residential/Map.aspx');
xhr.setRequestHeader('Connection', 'keep-alive');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send(data);

12
test/fixtures/javascript-xhr/post_xpost.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
const data = '{"keywords":"php","page":1,"searchMode":1}';
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'http://localhost:28139/api/xxxxxxxxxxxxxxxx');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send(data);

9
test/fixtures/javascript-xhr/repeated_query_key.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', 'http://localhost:28139?key=one&key=two');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

9
test/fixtures/javascript-xhr/strange_http_method.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('wHat', 'http://localhost:28139');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

9
test/fixtures/javascript-xhr/upload_file.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('PUT', 'http://localhost:28139/file.txt');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

9
test/fixtures/javascript-xhr/url_query.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', 'http://localhost:28139?foo=bar&baz=qux');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();

View File

@ -1,5 +1,6 @@
import axios from 'axios';
import { FormData } from 'form-data';
import FormData from 'form-data';
const form = new FormData();
form.append('from', 'test@tester.com');
form.append('to', 'devs@tester.net');

View File

@ -1,6 +1,7 @@
import axios from 'axios';
import { FormData } from 'form-data';
import FormData from 'form-data';
import { fs } from 'fs';
const form = new FormData();
form.append('file1', fs.readFileSync('./test/fixtures/curl_commands/delete.sh'), './test/fixtures/curl_commands/delete.sh');

View File

@ -1,6 +1,7 @@
import axios from 'axios';
import { FormData } from 'form-data';
import FormData from 'form-data';
import { fs } from 'fs';
const form = new FormData();
form.append('file1', fs.readFileSync('./test/fixtures/curl_commands/delete.sh'), './test/fixtures/curl_commands/delete.sh');
form.append('form1', 'form+data+1');

View File

@ -1,5 +1,6 @@
import axios from 'axios';
import { FormData } from 'form-data';
import FormData from 'form-data';
const form = new FormData();
form.append('d1', 'data1');
form.append('d2', 'data');

View File

@ -1,6 +1,7 @@
import axios from 'axios';
import { FormData } from 'form-data';
import FormData from 'form-data';
import { fs } from 'fs';
const form = new FormData();
form.append('attributes', '{"name":"tigers.jpeg", "parent":{"id":"11446498"}}');
form.append('file', fs.readFileSync('myfile.jpg'), 'myfile.jpg');

View File

@ -1,6 +1,7 @@
import axios from 'axios';
import { FormData } from 'form-data';
import FormData from 'form-data';
import { fs } from 'fs';
const form = new FormData();
form.append('attributes', '{"name":"tigers.jpeg", "parent":{"id":"11446498"}}');
form.append('file', fs.readFileSync('myfile.jpg'), 'myfile.jpg');

View File

@ -1,5 +1,6 @@
import axios from 'axios';
import { FormData } from 'form-data';
import FormData from 'form-data';
const form = new FormData();
form.append('username', 'davidwalsh');
form.append('password', 'something');

View File

@ -1,6 +1,7 @@
import axios from 'axios';
import { FormData } from 'form-data';
import FormData from 'form-data';
import { fs } from 'fs';
const form = new FormData();
form.append('image', fs.readFileSync('image.jpg'), 'image.jpg');

View File

@ -1,6 +1,7 @@
import axios from 'axios';
import { FormData } from 'form-data';
import FormData from 'form-data';
import { fs } from 'fs';
const form = new FormData();
form.append('files', fs.readFileSync('47.htz'), '47.htz');
form.append('name', '47');

27
test/fixtures/node-http/commented_json_with_session.js generated vendored Normal file
View File

@ -0,0 +1,27 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
// req.write('{ }');
req.write(JSON.stringify({}));
req.end();

20
test/fixtures/node-http/get_basic_auth.js generated vendored Normal file
View File

@ -0,0 +1,20 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/',
auth: 'some_username:some_password'
};
const req = http.get(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

14
test/fixtures/node-http/get_cert_cacert.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
import http from 'http';
const req = http.get('http://localhost:28139/', function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

14
test/fixtures/node-http/get_complex_url_params.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
import http from 'http';
const req = http.get('http://localhost:28139/house-sitting/?page=1&available=&available=1&location=0&city%5Bid%5D=0&city%5Blocality%5D=&city%5Blocality_text%5D=&city%5Badministrative_area_level_2%5D=&city%5Badministrative_area_level_2_text%5D=&city%5Badministrative_area_level_1%5D=&city%5Badministrative_area_level_1_text%5D=&city%5Bcountry%5D=&city%5Bcountry_text%5D=&city%5Blatitude%5D=&city%5Blongitude%5D=&city%5Bzoom%5D=&city%5Bname%5D=&region%5Bid%5D=0&region%5Blocality%5D=&region%5Blocality_text%5D=&region%5Badministrative_area_level_2%5D=&region%5Badministrative_area_level_2_text%5D=&region%5Badministrative_area_level_1%5D=&region%5Badministrative_area_level_1_text%5D=&region%5Bcountry%5D=&region%5Bcountry_text%5D=&region%5Blatitude%5D=&region%5Blongitude%5D=&region%5Bzoom%5D=&region%5Bname%5D=&country=&environment=&population=&period=0&date=2017-03-03&datestart=2017-03-03&dateend=2017-06-24&season=&duration=&isfd=&stopover=', function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

19
test/fixtures/node-http/get_max_time.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
timeout: 20000
};
const req = http.get(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

View File

@ -0,0 +1,19 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
timeout: 6720
};
const req = http.get(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

23
test/fixtures/node-http/get_referer.js generated vendored Normal file
View File

@ -0,0 +1,23 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'SimCity',
'Referer': 'https://website.com'
}
};
const req = http.get(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

27
test/fixtures/node-http/get_with_all_numerical_data.js generated vendored Normal file
View File

@ -0,0 +1,27 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/CurlToNode',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write('18233982904');
req.end();

28
test/fixtures/node-http/get_with_browser_headers.js generated vendored Normal file
View File

@ -0,0 +1,28 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/',
headers: {
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Referer': 'http://www.wikipedia.org/',
'Cookie': 'GeoIP=US:Albuquerque:35.1241:-106.7675:v4; uls-previous-languages=%5B%22en%22%5D; mediaWiki.user.sessionId=VaHaeVW3m0ymvx9kacwshZIDkv8zgF9y; centralnotice_buckets_by_campaign=%7B%22C14_enUS_dsk_lw_FR%22%3A%7B%22val%22%3A%220%22%2C%22start%22%3A1412172000%2C%22end%22%3A1422576000%7D%2C%22C14_en5C_dec_dsk_FR%22%3A%7B%22val%22%3A3%2C%22start%22%3A1417514400%2C%22end%22%3A1425290400%7D%2C%22C14_en5C_bkup_dsk_FR%22%3A%7B%22val%22%3A1%2C%22start%22%3A1417428000%2C%22end%22%3A1425290400%7D%7D; centralnotice_bannercount_fr12=22; centralnotice_bannercount_fr12-wait=14',
'Connection': 'keep-alive'
}
};
const req = http.get(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

22
test/fixtures/node-http/get_with_data.js generated vendored Normal file
View File

@ -0,0 +1,22 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/synthetics/api/v3/monitors?test=2&limit=100&w=4',
headers: {
'X-Api-Key': '123456789'
}
};
const req = http.get(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

25
test/fixtures/node-http/get_with_data2.js generated vendored Normal file
View File

@ -0,0 +1,25 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/v2/alerts_policy_channels.json?policy_id=policy_id&channel_ids=channel_id',
method: 'PUT',
headers: {
'X-Api-Key': '{admin_api_key}',
'Content-Type': 'application/json'
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.end();

23
test/fixtures/node-http/get_with_env_var.js generated vendored Normal file
View File

@ -0,0 +1,23 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/v2/images?type=distribution',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + process.env['DO_API_TOKEN']
}
};
const req = http.get(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

31
test/fixtures/node-http/get_with_form.js generated vendored Normal file
View File

@ -0,0 +1,31 @@
import http from 'http';
import FormData from 'form-data';
const form = new FormData();
form.append('from', 'test@tester.com');
form.append('to', 'devs@tester.net');
form.append('subject', 'Hello');
form.append('text', 'Testing the converter!');
const options = {
hostname: 'localhost:28139',
path: '/v3',
method: 'POST',
auth: 'test:',
headers: form.getHeaders()
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
form.pipe(req);

14
test/fixtures/node-http/max_redirs.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
import http from 'http';
const req = http.get('http://localhost:28139', function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

29
test/fixtures/node-http/multiline_post_with_data.js generated vendored Normal file
View File

@ -0,0 +1,29 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/echo/html/',
headers: {
'Origin': 'http://fiddle.jshell.net',
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(new URLSearchParams({
'msg1': 'value1',
'msg2': 'value2'
}).toString());
req.end();

32
test/fixtures/node-http/multipart_post.js generated vendored Normal file
View File

@ -0,0 +1,32 @@
import http from 'http';
import FormData from 'form-data';
import { fs } from 'fs';
const form = new FormData();
form.append('attributes', '{"name":"tigers.jpeg", "parent":{"id":"11446498"}}');
form.append('file', fs.readFileSync('myfile.jpg'), 'myfile.jpg');
const options = {
hostname: 'localhost:28139',
path: '/api/2.0/files/content',
method: 'POST',
headers: {
'Authorization': 'Bearer ACCESS_TOKEN',
...form.getHeaders()
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
form.pipe(req);

25
test/fixtures/node-http/post_empty.js generated vendored Normal file
View File

@ -0,0 +1,25 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write('');
req.end();

View File

@ -0,0 +1,26 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/post',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write('secret=*%5*!');
req.end();

37
test/fixtures/node-http/post_with_urlencoded_data.js generated vendored Normal file
View File

@ -0,0 +1,37 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/echo/html/',
method: 'POST',
headers: {
'Origin': 'http://fiddle.jshell.net',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': '*/*',
'Referer': 'http://fiddle.jshell.net/_display/',
'X-Requested-With': 'XMLHttpRequest',
'Connection': 'keep-alive'
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(new URLSearchParams({
'msg1': 'wow',
'msg2': 'such'
}).toString());
req.end();

View File

@ -0,0 +1,55 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/api/Listing.svc/PropertySearch_Post',
method: 'POST',
headers: {
'Origin': 'http://www.realtor.ca',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': '*/*',
'Referer': 'http://www.realtor.ca/Residential/Map.aspx',
'Connection': 'keep-alive'
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(new URLSearchParams({
'CultureId': '1',
'ApplicationId': '1',
'RecordsPerPage': '200',
'MaximumResults': '200',
'PropertyTypeId': '300',
'TransactionTypeId': '2',
'StoreyRange': '0-0',
'BuildingTypeId': '1',
'BedRange': '0-0',
'BathRange': '0-0',
'LongitudeMin': '-79.3676805496215',
'LongitudeMax': '-79.27300930023185',
'LatitudeMin': '43.660358732823845',
'LatitudeMax': '43.692390574029936',
'SortOrder': 'A',
'SortBy': '1',
'viewState': 'm',
'Longitude': '-79.4107246398925',
'Latitude': '43.6552047278685',
'ZoomLevel': '13',
'CurrentPage': '1'
}).toString());
req.end();

26
test/fixtures/node-http/post_xpost.js generated vendored Normal file
View File

@ -0,0 +1,26 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/api/xxxxxxxxxxxxxxxx',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write('{"keywords":"php","page":1,"searchMode":1}');
req.end();

14
test/fixtures/node-http/repeated_query_key.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
import http from 'http';
const req = http.get('http://localhost:28139?key=one&key=two', function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

20
test/fixtures/node-http/strange_http_method.js generated vendored Normal file
View File

@ -0,0 +1,20 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
method: 'wHat'
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.end();

21
test/fixtures/node-http/upload_file.js generated vendored Normal file
View File

@ -0,0 +1,21 @@
import http from 'http';
const options = {
hostname: 'localhost:28139',
path: '/file.txt',
method: 'PUT'
};
const req = http.request(options, function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.end();

14
test/fixtures/node-http/url_query.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
import http from 'http';
const req = http.get('http://localhost:28139?foo=bar&baz=qux', function (res) {
const chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});

View File

@ -0,0 +1,11 @@
import request from 'superagent';
request
.post('http://localhost:28139')
.set('Accept', 'application/json')
.type('json')
// .send('{ }')
.send({})
.then(res => {
console.log(res.body);
});

8
test/fixtures/node-superagent/get_basic_auth.js generated vendored Normal file
View File

@ -0,0 +1,8 @@
import request from 'superagent';
request
.get('http://localhost:28139/')
.auth('some_username', 'some_password')
.then(res => {
console.log(res.body);
});

10
test/fixtures/node-superagent/get_cert_cacert.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
import request from 'superagent';
import { fs } from 'fs';
request
.get('http://localhost:28139/')
.cert(fs.readFileSync('/path/to/the/cert'))
.ca(fs.readFileSync('/path/to/ca-bundle.crt'))
.then(res => {
console.log(res.body);
});

View File

@ -0,0 +1,49 @@
import request from 'superagent';
request
.get('http://localhost:28139/house-sitting/')
.query({
'page': '1',
'available': ['', '1'],
'location': '0',
'city[id]': '0',
'city[locality]': '',
'city[locality_text]': '',
'city[administrative_area_level_2]': '',
'city[administrative_area_level_2_text]': '',
'city[administrative_area_level_1]': '',
'city[administrative_area_level_1_text]': '',
'city[country]': '',
'city[country_text]': '',
'city[latitude]': '',
'city[longitude]': '',
'city[zoom]': '',
'city[name]': '',
'region[id]': '0',
'region[locality]': '',
'region[locality_text]': '',
'region[administrative_area_level_2]': '',
'region[administrative_area_level_2_text]': '',
'region[administrative_area_level_1]': '',
'region[administrative_area_level_1_text]': '',
'region[country]': '',
'region[country_text]': '',
'region[latitude]': '',
'region[longitude]': '',
'region[zoom]': '',
'region[name]': '',
'country': '',
'environment': '',
'population': '',
'period': '0',
'date': '2017-03-03',
'datestart': '2017-03-03',
'dateend': '2017-06-24',
'season': '',
'duration': '',
'isfd': '',
'stopover': ''
})
.then(res => {
console.log(res.body);
});

8
test/fixtures/node-superagent/get_max_time.js generated vendored Normal file
View File

@ -0,0 +1,8 @@
import request from 'superagent';
request
.get('http://localhost:28139')
.timeout(20000)
.then(res => {
console.log(res.body);
});

View File

@ -0,0 +1,8 @@
import request from 'superagent';
request
.get('http://localhost:28139')
.timeout({ response: 13999.9deadline: 6720 })
.then(res => {
console.log(res.body);
});

10
test/fixtures/node-superagent/get_referer.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
import request from 'superagent';
request
.get('http://localhost:28139')
.set('X-Requested-With', 'XMLHttpRequest')
.set('User-Agent', 'SimCity')
.set('Referer', 'https://website.com')
.then(res => {
console.log(res.body);
});

View File

@ -0,0 +1,10 @@
import request from 'superagent';
request
.post('http://localhost:28139/CurlToNode')
.set('Accept', 'application/json')
.type('json')
.send('18233982904')
.then(res => {
console.log(res.body);
});

View File

@ -0,0 +1,14 @@
import request from 'superagent';
request
.get('http://localhost:28139/')
.set('Accept-Encoding', 'gzip, deflate, sdch')
.set('Accept-Language', 'en-US,en;q=0.8')
.set('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36')
.set('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
.set('Referer', 'http://www.wikipedia.org/')
.set('Cookie', 'GeoIP=US:Albuquerque:35.1241:-106.7675:v4; uls-previous-languages=%5B%22en%22%5D; mediaWiki.user.sessionId=VaHaeVW3m0ymvx9kacwshZIDkv8zgF9y; centralnotice_buckets_by_campaign=%7B%22C14_enUS_dsk_lw_FR%22%3A%7B%22val%22%3A%220%22%2C%22start%22%3A1412172000%2C%22end%22%3A1422576000%7D%2C%22C14_en5C_dec_dsk_FR%22%3A%7B%22val%22%3A3%2C%22start%22%3A1417514400%2C%22end%22%3A1425290400%7D%2C%22C14_en5C_bkup_dsk_FR%22%3A%7B%22val%22%3A1%2C%22start%22%3A1417428000%2C%22end%22%3A1425290400%7D%7D; centralnotice_bannercount_fr12=22; centralnotice_bannercount_fr12-wait=14')
.set('Connection', 'keep-alive')
.then(res => {
console.log(res.body);
});

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