@readme/httpsnippet 9.0.0 → 10.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-R65NNSSK.js → chunk-M6LAZDIU.js} +21 -33
- package/dist/chunk-M6LAZDIU.js.map +1 -0
- package/dist/{index-D_ySc8Oi.d.ts → index-BTuTGf5t.d.ts} +1 -1
- package/dist/{index-BRpINGne.d.cts → index-C-fCLOHv.d.cts} +1 -1
- package/dist/index.cjs +21 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/targets/index.cjs +20 -32
- package/dist/targets/index.cjs.map +1 -1
- package/dist/targets/index.d.cts +1 -1
- package/dist/targets/index.d.ts +1 -1
- package/dist/targets/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-R65NNSSK.js.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import 'har-format';
|
|
2
2
|
import './helpers/reducer.cjs';
|
|
3
|
-
export { n as HTTPSnippet, m as HTTPSnippetOptions, H as HarRequest, l as Request, R as RequestExtras, j as addClientPlugin, g as addTarget, k as addTargetClient, o as availableTargets, p as extname } from './index-
|
|
3
|
+
export { n as HTTPSnippet, m as HTTPSnippetOptions, H as HarRequest, l as Request, R as RequestExtras, j as addClientPlugin, g as addTarget, k as addTargetClient, o as availableTargets, p as extname } from './index-C-fCLOHv.cjs';
|
|
4
4
|
import 'node:url';
|
|
5
5
|
import './helpers/code-builder.cjs';
|
|
6
6
|
import 'type-fest';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import 'har-format';
|
|
2
2
|
import './helpers/reducer.js';
|
|
3
|
-
export { n as HTTPSnippet, m as HTTPSnippetOptions, H as HarRequest, l as Request, R as RequestExtras, j as addClientPlugin, g as addTarget, k as addTargetClient, o as availableTargets, p as extname } from './index-
|
|
3
|
+
export { n as HTTPSnippet, m as HTTPSnippetOptions, H as HarRequest, l as Request, R as RequestExtras, j as addClientPlugin, g as addTarget, k as addTargetClient, o as availableTargets, p as extname } from './index-BTuTGf5t.js';
|
|
4
4
|
import 'node:url';
|
|
5
5
|
import './helpers/code-builder.js';
|
|
6
6
|
import 'type-fest';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { reducer } from './chunk-KT7MO6Z4.js';
|
|
2
|
-
import { targets, getHeaderName } from './chunk-
|
|
3
|
-
export { addClientPlugin, addTarget, addTargetClient } from './chunk-
|
|
2
|
+
import { targets, getHeaderName } from './chunk-M6LAZDIU.js';
|
|
3
|
+
export { addClientPlugin, addTarget, addTargetClient } from './chunk-M6LAZDIU.js';
|
|
4
4
|
import './chunk-Y7NI4MMY.js';
|
|
5
5
|
import { parse, format } from 'url';
|
|
6
6
|
import { stringify } from 'qs';
|
|
@@ -224,7 +224,7 @@ var HTTPSnippet = class {
|
|
|
224
224
|
}
|
|
225
225
|
const { convert } = target.clientsById[clientId || target.info.default];
|
|
226
226
|
const results = this.requests.map((request) => convert(request, options));
|
|
227
|
-
return results
|
|
227
|
+
return results;
|
|
228
228
|
}
|
|
229
229
|
};
|
|
230
230
|
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/helpers/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAKA,SAAS,UAAU,WAAW,SAAS,gBAAgB;AAEvD,SAAS,aAAa,sBAAsB;;;ACCrC,IAAM,mBAAmB,MAC9B,OAAO,KAAK,OAAO,EAAE,IAAqB,eAAa;AAAA,EACrD,GAAG,QAAQ,QAAoB,EAAE;AAAA,EACjC,SAAS,OAAO,KAAK,QAAQ,QAAoB,EAAE,WAAW,EAAE;AAAA,IAC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;AAGA,UAAM,MAAM,UAAU;AAAA,MACpB,GAAG;AAAA,MACH,OAAO;AAAA,MACP,QAAQ;AAAA,IACV,CAAC;AAED,UAAM,UAAU,UAAU;AAAA,MACxB,GAAG;AAAA,MACH,GAAG;AAAA,IACL,CAAC;AAED,WAAO;AAAA,MACL,GAAG;AAAA,MACH;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,QAAQ,UAAoB,UAAqB,SAAe;AAC9D,QAAI,CAAC,KAAK,YAAY;AACpB,WAAK,KAAK;AAAA,IACZ;AAEA,QAAI,CAAC,WAAW,UAAU;AACxB,gBAAU;AAAA,IACZ;AAEA,UAAM,SAAS,QAAQ,QAAQ;AAC/B,QAAI,CAAC,QAAQ;AACX,aAAO;AAAA,IACT;AAEA,UAAM,EAAE,QAAQ,IAAI,OAAO,YAAY,YAAY,OAAO,KAAK,OAAO;AACtE,UAAM,UAAU,KAAK,SAAS,IAAI,aAAW,QAAQ,SAAS,OAAO,CAAC;AACtE,WAAO,QAAQ,WAAW,IAAI,QAAQ,CAAC,IAAI;AAAA,EAC7C;AACF","sourcesContent":["import type { ReducedHelperObject } from './helpers/reducer.js';\nimport type { ClientId, TargetId } from './targets/index.js';\nimport type { Param, PostDataCommon, Request as NpmHarRequest } from 'har-format';\nimport type { UrlWithParsedQuery } from 'node:url';\n\nimport { format as urlFormat, parse as urlParse } from 'node:url';\n\nimport { stringify as queryStringify } from 'qs';\n\nimport { getHeaderName } from './helpers/headers.js';\nimport { reducer } from './helpers/reducer.js';\nimport { targets } from './targets/index.js';\n\nexport { availableTargets, extname } from './helpers/utils.js';\nexport { addTarget, addTargetClient, addClientPlugin } from './targets/index.js';\n\n/** is this wrong? yes. according to the spec (http://www.softwareishard.com/blog/har-12-spec/#postData) it's technically wrong since `params` and `text` are (by the spec) mutually exclusive. However, in practice, this is not what is often the case.\n *\n * In general, this library takes a _descriptive_ rather than _perscriptive_ approach (see https://amyrey.web.unc.edu/classes/ling-101-online/tutorials/understanding-prescriptive-vs-descriptive-grammar/).\n *\n * Then, in addition to that, it really adds to complexity with TypeScript (TypeScript takes this constraint very very seriously) in a way that's not actually super useful. So, we treat this object as though it could have both or either of `params` and/or `text`.\n */\ntype PostDataBase = PostDataCommon & {\n params?: Param[];\n text?: string;\n};\n\nexport type HarRequest = Omit<NpmHarRequest, 'postData'> & { postData: PostDataBase };\n\nexport interface RequestExtras {\n allHeaders: ReducedHelperObject;\n cookiesObj: ReducedHelperObject;\n fullUrl: string;\n headersObj: ReducedHelperObject;\n postData: PostDataBase & {\n boundary?: string;\n jsonObj?: ReducedHelperObject;\n paramsObj?: ReducedHelperObject;\n };\n queryObj: ReducedHelperObject;\n uriObj: UrlWithParsedQuery;\n}\n\nexport type Request = HarRequest & RequestExtras;\n\ninterface Entry {\n request: Partial<HarRequest>;\n}\n\ninterface HarEntry {\n log: {\n creator: {\n name: string;\n version: string;\n };\n entries: Entry[];\n version: string;\n };\n}\n\nexport interface HTTPSnippetOptions {\n harIsAlreadyEncoded?: boolean;\n}\n\nconst isHarEntry = (value: any): value is HarEntry =>\n typeof value === 'object' &&\n 'log' in value &&\n typeof value.log === 'object' &&\n 'entries' in value.log &&\n Array.isArray(value.log.entries);\n\nexport class HTTPSnippet {\n initCalled = false;\n\n entries: Entry[] = [];\n\n requests: Request[] = [];\n\n options: HTTPSnippetOptions = {};\n\n constructor(input: HarEntry | HarRequest, opts: HTTPSnippetOptions = {}) {\n this.options = {\n harIsAlreadyEncoded: false,\n ...opts,\n };\n\n // prep the main container\n this.requests = [];\n\n // is it har?\n if (isHarEntry(input)) {\n this.entries = input.log.entries;\n } else {\n this.entries = [\n {\n request: input,\n },\n ];\n }\n }\n\n init() {\n this.initCalled = true;\n\n this.requests = this.entries.map(({ request }) => {\n // add optional properties to make validation successful\n const req = {\n bodySize: 0,\n headersSize: 0,\n headers: [],\n cookies: [],\n httpVersion: 'HTTP/1.1',\n queryString: [],\n postData: {\n mimeType: request.postData?.mimeType || 'application/octet-stream',\n },\n ...request,\n };\n\n // Per the HAR spec `mimeType` needs to always be present if we have a `postData` object.\n if (req.postData && !req.postData.mimeType) {\n req.postData.mimeType = 'application/octet-stream';\n }\n\n return this.prepare(req as HarRequest, this.options);\n });\n\n return this;\n }\n\n prepare(harRequest: HarRequest, options: HTTPSnippetOptions) {\n const request: Request = {\n ...harRequest,\n fullUrl: '',\n uriObj: {} as UrlWithParsedQuery,\n queryObj: {},\n headersObj: {},\n cookiesObj: {},\n allHeaders: {},\n };\n\n // construct query objects\n if (request.queryString && request.queryString.length) {\n request.queryObj = request.queryString.reduce(reducer, {});\n }\n\n // construct headers objects\n if (request.headers && request.headers.length) {\n const http2VersionRegex = /^HTTP\\/2/;\n request.headersObj = request.headers.reduce((accumulator, { name, value }) => {\n const headerName = http2VersionRegex.exec(request.httpVersion) ? name.toLocaleLowerCase() : name;\n return {\n ...accumulator,\n [headerName]: value,\n };\n }, {});\n }\n\n // construct headers objects\n if (request.cookies && request.cookies.length) {\n request.cookiesObj = request.cookies.reduceRight(\n (accumulator, { name, value }) => ({\n ...accumulator,\n [name]: value,\n }),\n {},\n );\n }\n\n // construct Cookie header\n const cookies = request.cookies?.map(({ name, value }) => {\n if (options.harIsAlreadyEncoded) {\n return `${name}=${value}`;\n }\n\n return `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n });\n\n if (cookies?.length) {\n request.allHeaders.cookie = cookies.join('; ');\n }\n\n switch (request.postData.mimeType) {\n case 'multipart/mixed':\n case 'multipart/related':\n case 'multipart/form-data':\n case 'multipart/alternative':\n // reset values\n request.postData.text = '';\n request.postData.mimeType = 'multipart/form-data';\n\n if (request.postData?.params) {\n const boundary = '---011000010111000001101001'; // this is binary for \"api\" (easter egg)\n const carriage = `${boundary}--`;\n const rn = '\\r\\n';\n\n /*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */\n const escape = (str: string) => str.replace(/\\n/g, '%0A').replace(/\\r/g, '%0D').replace(/\"/g, '%22');\n const normalizeLinefeeds = (value: string) => value.replace(/\\r?\\n|\\r/g, '\\r\\n');\n\n const payload = [`--${boundary}`];\n request.postData?.params.forEach((param, i) => {\n const name = param.name;\n const value = param.value || '';\n const filename = param.fileName || null;\n const contentType = param.contentType || 'application/octet-stream';\n\n if (filename) {\n payload.push(\n `Content-Disposition: form-data; name=\"${escape(normalizeLinefeeds(name))}\"; filename=\"${filename}\"`,\n );\n payload.push(`Content-Type: ${contentType}`);\n } else {\n payload.push(`Content-Disposition: form-data; name=\"${escape(normalizeLinefeeds(name))}\"`);\n }\n\n payload.push('');\n payload.push(normalizeLinefeeds(value));\n\n if (i !== (request.postData.params as Param[]).length - 1) {\n payload.push(`--${boundary}`);\n }\n });\n\n payload.push(`--${carriage}`);\n\n request.postData.boundary = boundary;\n request.postData.text = payload.join(rn);\n\n // Since headers are case-sensitive we need to see if there's an existing `Content-Type` header that we can override.\n const contentTypeHeader = getHeaderName(request.headersObj, 'content-type') || 'content-type';\n\n request.headersObj[contentTypeHeader] = `multipart/form-data; boundary=${boundary}`;\n }\n break;\n\n case 'application/x-www-form-urlencoded':\n if (!request.postData.params) {\n request.postData.text = '';\n } else {\n // @ts-expect-error the `har-format` types make this challenging\n request.postData.paramsObj = request.postData.params.reduce(reducer, {});\n\n // always overwrite\n request.postData.text = queryStringify(request.postData.paramsObj);\n }\n break;\n\n case 'text/json':\n case 'text/x-json':\n case 'application/json':\n case 'application/x-json':\n request.postData.mimeType = 'application/json';\n\n if (request.postData.text) {\n try {\n request.postData.jsonObj = JSON.parse(request.postData.text);\n } catch (e) {\n // force back to `text/plain` if headers have proper content-type value, then this should also work\n request.postData.mimeType = 'text/plain';\n }\n }\n break;\n }\n\n // create allHeaders object\n const allHeaders = {\n ...request.allHeaders,\n ...request.headersObj,\n };\n\n const urlWithParsedQuery = urlParse(request.url, true, true); //?\n\n // query string key/value pairs in with literal querystrings containd within the url\n request.queryObj = {\n ...request.queryObj,\n ...(urlWithParsedQuery.query as ReducedHelperObject),\n }; //?\n\n // reset uriObj values for a clean url\n let search;\n if (options.harIsAlreadyEncoded) {\n search = queryStringify(request.queryObj, {\n encode: false,\n indices: false,\n });\n } else {\n search = queryStringify(request.queryObj, {\n indices: false,\n });\n }\n\n const uriObj = {\n ...urlWithParsedQuery,\n query: request.queryObj,\n search,\n path: search ? `${urlWithParsedQuery.pathname}?${search}` : urlWithParsedQuery.pathname,\n };\n\n // keep the base url clean of queryString\n const url = urlFormat({\n ...urlWithParsedQuery,\n query: null,\n search: null,\n }); //?\n\n const fullUrl = urlFormat({\n ...urlWithParsedQuery,\n ...uriObj,\n }); //?\n\n return {\n ...request,\n allHeaders,\n fullUrl,\n url,\n uriObj,\n };\n }\n\n convert(targetId: TargetId, clientId?: ClientId, options?: any) {\n if (!this.initCalled) {\n this.init();\n }\n\n if (!options && clientId) {\n options = clientId;\n }\n\n const target = targets[targetId];\n if (!target) {\n return false;\n }\n\n const { convert } = target.clientsById[clientId || target.info.default];\n const results = this.requests.map(request => convert(request, options));\n return results.length === 1 ? results[0] : results;\n }\n}\n","import type { ClientId, ClientInfo, TargetId, TargetInfo } from '../targets/index.js';\n\nimport { targets } from '../targets/index.js';\n\nexport interface AvailableTarget extends TargetInfo {\n clients: ClientInfo[];\n}\n\nexport const availableTargets = () =>\n Object.keys(targets).map<AvailableTarget>(targetId => ({\n ...targets[targetId as TargetId].info,\n clients: Object.keys(targets[targetId as TargetId].clientsById).map(\n clientId => targets[targetId as TargetId].clientsById[clientId].info,\n ),\n }));\n\nexport const extname = (targetId: TargetId, clientId: ClientId) => {\n const target = targets[targetId];\n if (!target) {\n return '';\n }\n\n return target.clientsById[clientId]?.info.extname || '';\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/helpers/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAKA,SAAS,UAAU,WAAW,SAAS,gBAAgB;AAEvD,SAAS,aAAa,sBAAsB;;;ACCrC,IAAM,mBAAmB,MAC9B,OAAO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AM,SAAS;AAAA,MACb,GAAG;AAAA,MACH,OAAO,QAAQ;AAAA,MACf;AAAA,MACA,MAAM,SAAS,GAAG,mBAAmB,QAAQ,IAAI,MAAM,KAAK,mBAAmB;AAAA,IACjF;AAGA,UAAM,MAAM,UAAU;AAAA,MACpB,GAAG;AAAA,MACH,OAAO;AAAA,MACP,QAAQ;AAAA,IACV,CAAC;AAED,UAAM,UAAU,UAAU;AAAA,MACxB,GAAG;AAAA,MACH,GAAG;AAAA,IACL,CAAC;AAED,WAAO;AAAA,MACL,GAAG;AAAA,MACH;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,QAAQ,UAAoB,UAAqB,SAAe;AAC9D,QAAI,CAAC,KAAK,YAAY;AACpB,WAAK,KAAK;AAAA,IACZ;AAEA,QAAI,CAAC,WAAW,UAAU;AACxB,gBAAU;AAAA,IACZ;AAEA,UAAM,SAAS,QAAQ,QAAQ;AAC/B,QAAI,CAAC,QAAQ;AACX,aAAO;AAAA,IACT;AAEA,UAAM,EAAE,QAAQ,IAAI,OAAO,YAAY,YAAY,OAAO,KAAK,OAAO;AACtE,UAAM,UAAU,KAAK,SAAS,IAAI,aAAW,QAAQ,SAAS,OAAO,CAAC;AACtE,WAAO;AAAA,EACT;AACF","sourcesContent":["import type { ReducedHelperObject } from './helpers/reducer.js';\nimport type { ClientId, TargetId } from './targets/index.js';\nimport type { Param, PostDataCommon, Request as NpmHarRequest } from 'har-format';\nimport type { UrlWithParsedQuery } from 'node:url';\n\nimport { format as urlFormat, parse as urlParse } from 'node:url';\n\nimport { stringify as queryStringify } from 'qs';\n\nimport { getHeaderName } from './helpers/headers.js';\nimport { reducer } from './helpers/reducer.js';\nimport { targets } from './targets/index.js';\n\nexport { availableTargets, extname } from './helpers/utils.js';\nexport { addTarget, addTargetClient, addClientPlugin } from './targets/index.js';\n\n/** is this wrong? yes. according to the spec (http://www.softwareishard.com/blog/har-12-spec/#postData) it's technically wrong since `params` and `text` are (by the spec) mutually exclusive. However, in practice, this is not what is often the case.\n *\n * In general, this library takes a _descriptive_ rather than _perscriptive_ approach (see https://amyrey.web.unc.edu/classes/ling-101-online/tutorials/understanding-prescriptive-vs-descriptive-grammar/).\n *\n * Then, in addition to that, it really adds to complexity with TypeScript (TypeScript takes this constraint very very seriously) in a way that's not actually super useful. So, we treat this object as though it could have both or either of `params` and/or `text`.\n */\ntype PostDataBase = PostDataCommon & {\n params?: Param[];\n text?: string;\n};\n\nexport type HarRequest = Omit<NpmHarRequest, 'postData'> & { postData: PostDataBase };\n\nexport interface RequestExtras {\n allHeaders: ReducedHelperObject;\n cookiesObj: ReducedHelperObject;\n fullUrl: string;\n headersObj: ReducedHelperObject;\n postData: PostDataBase & {\n boundary?: string;\n jsonObj?: ReducedHelperObject;\n paramsObj?: ReducedHelperObject;\n };\n queryObj: ReducedHelperObject;\n uriObj: UrlWithParsedQuery;\n}\n\nexport type Request = HarRequest & RequestExtras;\n\ninterface Entry {\n request: Partial<HarRequest>;\n}\n\ninterface HarEntry {\n log: {\n creator: {\n name: string;\n version: string;\n };\n entries: Entry[];\n version: string;\n };\n}\n\nexport interface HTTPSnippetOptions {\n harIsAlreadyEncoded?: boolean;\n}\n\nconst isHarEntry = (value: any): value is HarEntry =>\n typeof value === 'object' &&\n 'log' in value &&\n typeof value.log === 'object' &&\n 'entries' in value.log &&\n Array.isArray(value.log.entries);\n\nexport class HTTPSnippet {\n initCalled = false;\n\n entries: Entry[] = [];\n\n requests: Request[] = [];\n\n options: HTTPSnippetOptions = {};\n\n constructor(input: HarEntry | HarRequest, opts: HTTPSnippetOptions = {}) {\n this.options = {\n harIsAlreadyEncoded: false,\n ...opts,\n };\n\n // prep the main container\n this.requests = [];\n\n // is it har?\n if (isHarEntry(input)) {\n this.entries = input.log.entries;\n } else {\n this.entries = [\n {\n request: input,\n },\n ];\n }\n }\n\n init() {\n this.initCalled = true;\n\n this.requests = this.entries.map(({ request }) => {\n // add optional properties to make validation successful\n const req = {\n bodySize: 0,\n headersSize: 0,\n headers: [],\n cookies: [],\n httpVersion: 'HTTP/1.1',\n queryString: [],\n postData: {\n mimeType: request.postData?.mimeType || 'application/octet-stream',\n },\n ...request,\n };\n\n // Per the HAR spec `mimeType` needs to always be present if we have a `postData` object.\n if (req.postData && !req.postData.mimeType) {\n req.postData.mimeType = 'application/octet-stream';\n }\n\n return this.prepare(req as HarRequest, this.options);\n });\n\n return this;\n }\n\n prepare(harRequest: HarRequest, options: HTTPSnippetOptions) {\n const request: Request = {\n ...harRequest,\n fullUrl: '',\n uriObj: {} as UrlWithParsedQuery,\n queryObj: {},\n headersObj: {},\n cookiesObj: {},\n allHeaders: {},\n };\n\n // construct query objects\n if (request.queryString && request.queryString.length) {\n request.queryObj = request.queryString.reduce(reducer, {});\n }\n\n // construct headers objects\n if (request.headers && request.headers.length) {\n const http2VersionRegex = /^HTTP\\/2/;\n request.headersObj = request.headers.reduce((accumulator, { name, value }) => {\n const headerName = http2VersionRegex.exec(request.httpVersion) ? name.toLocaleLowerCase() : name;\n return {\n ...accumulator,\n [headerName]: value,\n };\n }, {});\n }\n\n // construct headers objects\n if (request.cookies && request.cookies.length) {\n request.cookiesObj = request.cookies.reduceRight(\n (accumulator, { name, value }) => ({\n ...accumulator,\n [name]: value,\n }),\n {},\n );\n }\n\n // construct Cookie header\n const cookies = request.cookies?.map(({ name, value }) => {\n if (options.harIsAlreadyEncoded) {\n return `${name}=${value}`;\n }\n\n return `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n });\n\n if (cookies?.length) {\n request.allHeaders.cookie = cookies.join('; ');\n }\n\n switch (request.postData.mimeType) {\n case 'multipart/mixed':\n case 'multipart/related':\n case 'multipart/form-data':\n case 'multipart/alternative':\n // reset values\n request.postData.text = '';\n request.postData.mimeType = 'multipart/form-data';\n\n if (request.postData?.params) {\n const boundary = '---011000010111000001101001'; // this is binary for \"api\" (easter egg)\n const carriage = `${boundary}--`;\n const rn = '\\r\\n';\n\n /*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */\n const escape = (str: string) => str.replace(/\\n/g, '%0A').replace(/\\r/g, '%0D').replace(/\"/g, '%22');\n const normalizeLinefeeds = (value: string) => value.replace(/\\r?\\n|\\r/g, '\\r\\n');\n\n const payload = [`--${boundary}`];\n request.postData?.params.forEach((param, i) => {\n const name = param.name;\n const value = param.value || '';\n const filename = param.fileName || null;\n const contentType = param.contentType || 'application/octet-stream';\n\n if (filename) {\n payload.push(\n `Content-Disposition: form-data; name=\"${escape(normalizeLinefeeds(name))}\"; filename=\"${filename}\"`,\n );\n payload.push(`Content-Type: ${contentType}`);\n } else {\n payload.push(`Content-Disposition: form-data; name=\"${escape(normalizeLinefeeds(name))}\"`);\n }\n\n payload.push('');\n payload.push(normalizeLinefeeds(value));\n\n if (i !== (request.postData.params as Param[]).length - 1) {\n payload.push(`--${boundary}`);\n }\n });\n\n payload.push(`--${carriage}`);\n\n request.postData.boundary = boundary;\n request.postData.text = payload.join(rn);\n\n // Since headers are case-sensitive we need to see if there's an existing `Content-Type` header that we can override.\n const contentTypeHeader = getHeaderName(request.headersObj, 'content-type') || 'content-type';\n\n request.headersObj[contentTypeHeader] = `multipart/form-data; boundary=${boundary}`;\n }\n break;\n\n case 'application/x-www-form-urlencoded':\n if (!request.postData.params) {\n request.postData.text = '';\n } else {\n // @ts-expect-error the `har-format` types make this challenging\n request.postData.paramsObj = request.postData.params.reduce(reducer, {});\n\n // always overwrite\n request.postData.text = queryStringify(request.postData.paramsObj);\n }\n break;\n\n case 'text/json':\n case 'text/x-json':\n case 'application/json':\n case 'application/x-json':\n request.postData.mimeType = 'application/json';\n\n if (request.postData.text) {\n try {\n request.postData.jsonObj = JSON.parse(request.postData.text);\n } catch (e) {\n // force back to `text/plain` if headers have proper content-type value, then this should also work\n request.postData.mimeType = 'text/plain';\n }\n }\n break;\n }\n\n // create allHeaders object\n const allHeaders = {\n ...request.allHeaders,\n ...request.headersObj,\n };\n\n const urlWithParsedQuery = urlParse(request.url, true, true); //?\n\n // query string key/value pairs in with literal querystrings containd within the url\n request.queryObj = {\n ...request.queryObj,\n ...(urlWithParsedQuery.query as ReducedHelperObject),\n }; //?\n\n // reset uriObj values for a clean url\n let search;\n if (options.harIsAlreadyEncoded) {\n search = queryStringify(request.queryObj, {\n encode: false,\n indices: false,\n });\n } else {\n search = queryStringify(request.queryObj, {\n indices: false,\n });\n }\n\n const uriObj = {\n ...urlWithParsedQuery,\n query: request.queryObj,\n search,\n path: search ? `${urlWithParsedQuery.pathname}?${search}` : urlWithParsedQuery.pathname,\n };\n\n // keep the base url clean of queryString\n const url = urlFormat({\n ...urlWithParsedQuery,\n query: null,\n search: null,\n }); //?\n\n const fullUrl = urlFormat({\n ...urlWithParsedQuery,\n ...uriObj,\n }); //?\n\n return {\n ...request,\n allHeaders,\n fullUrl,\n url,\n uriObj,\n };\n }\n\n convert(targetId: TargetId, clientId?: ClientId, options?: any) {\n if (!this.initCalled) {\n this.init();\n }\n\n if (!options && clientId) {\n options = clientId;\n }\n\n const target = targets[targetId];\n if (!target) {\n return false;\n }\n\n const { convert } = target.clientsById[clientId || target.info.default];\n const results = this.requests.map(request => convert(request, options));\n return results;\n }\n}\n","import type { ClientId, ClientInfo, TargetId, TargetInfo } from '../targets/index.js';\n\nimport { targets } from '../targets/index.js';\n\nexport interface AvailableTarget extends TargetInfo {\n clients: ClientInfo[];\n}\n\nexport const availableTargets = () =>\n Object.keys(targets).map<AvailableTarget>(targetId => ({\n ...targets[targetId as TargetId].info,\n clients: Object.keys(targets[targetId as TargetId].clientsById).map(\n clientId => targets[targetId as TargetId].clientsById[clientId].info,\n ),\n }));\n\nexport const extname = (targetId: TargetId, clientId: ClientId) => {\n const target = targets[targetId];\n if (!target) {\n return '';\n }\n\n return target.clientsById[clientId]?.info.extname || '';\n};\n"]}
|
package/dist/targets/index.cjs
CHANGED
|
@@ -3273,19 +3273,19 @@ var literalRepresentation3 = (value, opts, indentLevel) => {
|
|
|
3273
3273
|
return value.toString();
|
|
3274
3274
|
default:
|
|
3275
3275
|
if (value === null || value === void 0) {
|
|
3276
|
-
return "";
|
|
3276
|
+
return "nil";
|
|
3277
3277
|
}
|
|
3278
3278
|
return `"${value.toString().replace(/"/g, '\\"')}"`;
|
|
3279
3279
|
}
|
|
3280
3280
|
};
|
|
3281
3281
|
|
|
3282
|
-
// src/targets/swift/
|
|
3283
|
-
var
|
|
3282
|
+
// src/targets/swift/urlsession/client.ts
|
|
3283
|
+
var urlsession = {
|
|
3284
3284
|
info: {
|
|
3285
|
-
key: "
|
|
3286
|
-
title: "
|
|
3287
|
-
link: "https://developer.apple.com/
|
|
3288
|
-
description: "Foundation's
|
|
3285
|
+
key: "urlsession",
|
|
3286
|
+
title: "URLSession",
|
|
3287
|
+
link: "https://developer.apple.com/documentation/foundation/urlsession",
|
|
3288
|
+
description: "Foundation's URLSession request",
|
|
3289
3289
|
extname: ".swift"
|
|
3290
3290
|
},
|
|
3291
3291
|
convert: ({ allHeaders, postData, fullUrl, method }, options) => {
|
|
@@ -3301,6 +3301,9 @@ var nsurlsession2 = {
|
|
|
3301
3301
|
hasBody: false
|
|
3302
3302
|
};
|
|
3303
3303
|
push("import Foundation");
|
|
3304
|
+
push("#if canImport(FoundationNetworking)");
|
|
3305
|
+
push(" import FoundationNetworking");
|
|
3306
|
+
push("#endif");
|
|
3304
3307
|
if (Object.keys(allHeaders).length) {
|
|
3305
3308
|
req.hasHeaders = true;
|
|
3306
3309
|
blank();
|
|
@@ -3313,9 +3316,9 @@ var nsurlsession2 = {
|
|
|
3313
3316
|
blank();
|
|
3314
3317
|
if (postData.params?.length) {
|
|
3315
3318
|
const [head, ...tail] = postData.params;
|
|
3316
|
-
push(
|
|
3319
|
+
push(`${tail.length > 0 ? "var" : "let"} postData = Data("${head.name}=${head.value}".utf8)`);
|
|
3317
3320
|
tail.forEach(({ name, value }) => {
|
|
3318
|
-
push(`postData.append("&${name}=${value}".
|
|
3321
|
+
push(`postData.append(Data("&${name}=${value}".utf8))`);
|
|
3319
3322
|
});
|
|
3320
3323
|
} else {
|
|
3321
3324
|
req.hasBody = false;
|
|
@@ -3325,7 +3328,7 @@ var nsurlsession2 = {
|
|
|
3325
3328
|
if (postData.jsonObj) {
|
|
3326
3329
|
push(`${literalDeclaration("parameters", postData.jsonObj, opts)} as [String : Any]`);
|
|
3327
3330
|
blank();
|
|
3328
|
-
push("let postData = JSONSerialization.data(withJSONObject: parameters, options: [])");
|
|
3331
|
+
push("let postData = try JSONSerialization.data(withJSONObject: parameters, options: [])");
|
|
3329
3332
|
}
|
|
3330
3333
|
break;
|
|
3331
3334
|
case "multipart/form-data":
|
|
@@ -3355,37 +3358,22 @@ var nsurlsession2 = {
|
|
|
3355
3358
|
break;
|
|
3356
3359
|
default:
|
|
3357
3360
|
blank();
|
|
3358
|
-
push(`let postData =
|
|
3361
|
+
push(`let postData = Data("${postData.text}".utf8)`);
|
|
3359
3362
|
}
|
|
3360
3363
|
}
|
|
3361
3364
|
blank();
|
|
3362
|
-
push(`
|
|
3363
|
-
push(" cachePolicy: .useProtocolCachePolicy,");
|
|
3364
|
-
push(
|
|
3365
|
-
// @ts-expect-error needs better types
|
|
3366
|
-
` timeoutInterval: ${parseInt(opts.timeout, 10).toFixed(1)})`
|
|
3367
|
-
);
|
|
3365
|
+
push(`var request = URLRequest(url: URL(string: "${fullUrl}")!)`);
|
|
3368
3366
|
push(`request.httpMethod = "${method}"`);
|
|
3369
3367
|
if (req.hasHeaders) {
|
|
3370
3368
|
push("request.allHTTPHeaderFields = headers");
|
|
3371
3369
|
}
|
|
3372
3370
|
if (req.hasBody) {
|
|
3373
|
-
push("request.httpBody = postData
|
|
3371
|
+
push("request.httpBody = postData");
|
|
3374
3372
|
}
|
|
3375
3373
|
blank();
|
|
3376
|
-
push("let
|
|
3377
|
-
push(
|
|
3378
|
-
"let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in"
|
|
3379
|
-
);
|
|
3380
|
-
push("if (error != nil) {", 1);
|
|
3381
|
-
push("print(error as Any)", 2);
|
|
3382
|
-
push("} else {", 1);
|
|
3383
|
-
push("let httpResponse = response as? HTTPURLResponse", 2);
|
|
3384
|
-
push("print(httpResponse)", 2);
|
|
3385
|
-
push("}", 1);
|
|
3386
|
-
push("})");
|
|
3374
|
+
push("let (data, response) = try await URLSession.shared.data(with: request)");
|
|
3375
|
+
push("print(String(decoding: data, as: UTF8.self))");
|
|
3387
3376
|
blank();
|
|
3388
|
-
push("dataTask.resume()");
|
|
3389
3377
|
return join();
|
|
3390
3378
|
}
|
|
3391
3379
|
};
|
|
@@ -3395,10 +3383,10 @@ var swift = {
|
|
|
3395
3383
|
info: {
|
|
3396
3384
|
key: "swift",
|
|
3397
3385
|
title: "Swift",
|
|
3398
|
-
default: "
|
|
3386
|
+
default: "urlsession"
|
|
3399
3387
|
},
|
|
3400
3388
|
clientsById: {
|
|
3401
|
-
|
|
3389
|
+
urlsession
|
|
3402
3390
|
}
|
|
3403
3391
|
};
|
|
3404
3392
|
|