@scalar/snippetz 0.9.0 → 0.9.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.
Files changed (36) hide show
  1. package/dist/clients/index.d.ts.map +1 -1
  2. package/dist/clients/index.js +2 -1
  3. package/dist/libs/http.d.ts +29 -0
  4. package/dist/libs/http.d.ts.map +1 -1
  5. package/dist/libs/http.js +53 -0
  6. package/dist/plugins/c/libcurl/libcurl.d.ts.map +1 -1
  7. package/dist/plugins/c/libcurl/libcurl.js +145 -5
  8. package/dist/plugins/go/native/native.d.ts.map +1 -1
  9. package/dist/plugins/go/native/native.js +1 -42
  10. package/dist/plugins/python/aiohttp/aiohttp.d.ts +6 -0
  11. package/dist/plugins/python/aiohttp/aiohttp.d.ts.map +1 -0
  12. package/dist/plugins/python/aiohttp/aiohttp.js +107 -0
  13. package/dist/plugins/python/aiohttp/index.d.ts +2 -0
  14. package/dist/plugins/python/aiohttp/index.d.ts.map +1 -0
  15. package/dist/plugins/python/aiohttp/index.js +1 -0
  16. package/dist/plugins/python/python3/python3.d.ts.map +1 -1
  17. package/dist/plugins/python/python3/python3.js +192 -5
  18. package/dist/plugins/python/requestsLike.d.ts +2 -0
  19. package/dist/plugins/python/requestsLike.d.ts.map +1 -1
  20. package/dist/plugins/python/requestsLike.js +9 -9
  21. package/dist/plugins/swift/nsurlsession/nsurlsession.d.ts.map +1 -1
  22. package/dist/plugins/swift/nsurlsession/nsurlsession.js +118 -5
  23. package/dist/snippetz.d.ts +2 -2
  24. package/package.json +7 -2
  25. package/dist/httpsnippet-lite/targets/c/libcurl/client.d.ts +0 -3
  26. package/dist/httpsnippet-lite/targets/c/libcurl/client.d.ts.map +0 -1
  27. package/dist/httpsnippet-lite/targets/c/libcurl/client.js +0 -74
  28. package/dist/httpsnippet-lite/targets/python/python3/client.d.ts +0 -12
  29. package/dist/httpsnippet-lite/targets/python/python3/client.d.ts.map +0 -1
  30. package/dist/httpsnippet-lite/targets/python/python3/client.js +0 -88
  31. package/dist/httpsnippet-lite/targets/swift/helpers.d.ts +0 -15
  32. package/dist/httpsnippet-lite/targets/swift/helpers.d.ts.map +0 -1
  33. package/dist/httpsnippet-lite/targets/swift/helpers.js +0 -70
  34. package/dist/httpsnippet-lite/targets/swift/nsurlsession/client.d.ts +0 -12
  35. package/dist/httpsnippet-lite/targets/swift/nsurlsession/client.d.ts.map +0 -1
  36. package/dist/httpsnippet-lite/targets/swift/nsurlsession/client.js +0 -128
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/clients/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAA;AA0CpD;;GAEG;AACH,eAAO,MAAM,OAAO,EAAE,MAAM,EA+H3B,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/clients/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAA;AA2CpD;;GAEG;AACH,eAAO,MAAM,OAAO,EAAE,MAAM,EA+H3B,CAAA"}
@@ -27,6 +27,7 @@ import { phpGuzzle } from '../plugins/php/guzzle/index.js';
27
27
  import { phpLaravel } from '../plugins/php/laravel/index.js';
28
28
  import { powershellRestmethod } from '../plugins/powershell/restmethod/index.js';
29
29
  import { powershellWebrequest } from '../plugins/powershell/webrequest/index.js';
30
+ import { pythonAiohttp } from '../plugins/python/aiohttp/index.js';
30
31
  import { pythonHttpxAsync, pythonHttpxSync } from '../plugins/python/httpx/index.js';
31
32
  import { pythonPython3 } from '../plugins/python/python3/index.js';
32
33
  import { pythonRequests } from '../plugins/python/requests/index.js';
@@ -135,7 +136,7 @@ export const clients = [
135
136
  key: 'python',
136
137
  title: 'Python',
137
138
  default: 'python3',
138
- clients: [pythonPython3, pythonRequests, pythonHttpxSync, pythonHttpxAsync],
139
+ clients: [pythonPython3, pythonRequests, pythonAiohttp, pythonHttpxSync, pythonHttpxAsync],
139
140
  },
140
141
  {
141
142
  key: 'r',
@@ -1,4 +1,16 @@
1
1
  import type { HarRequest } from '@scalar/types/snippetz';
2
+ type HeaderPair = {
3
+ name: string;
4
+ value: string;
5
+ };
6
+ type NameValuePair = {
7
+ name: string;
8
+ value: string;
9
+ };
10
+ type NameOptionalValuePair = {
11
+ name: string;
12
+ value?: string;
13
+ };
2
14
  /**
3
15
  * Normalizes the request object with defaults
4
16
  */
@@ -12,6 +24,22 @@ export declare function buildQueryString(queryParams?: Array<{
12
24
  name: string;
13
25
  value: string;
14
26
  }>): string;
27
+ /**
28
+ * Normalizes a request method.
29
+ */
30
+ export declare const normalizeMethod: (method?: string) => string;
31
+ /**
32
+ * Normalizes URL formatting while preserving origin-only paths.
33
+ */
34
+ export declare const normalizeUrl: (url: string) => string;
35
+ /**
36
+ * Joins URL and query string while preserving existing query values.
37
+ */
38
+ export declare const joinUrlAndQuery: (url: string, queryString?: NameValuePair[]) => string;
39
+ /**
40
+ * Collects deduplicated headers and optional cookie headers.
41
+ */
42
+ export declare const collectHeaders: (headers?: NameOptionalValuePair[], cookies?: NameValuePair[]) => HeaderPair[];
15
43
  /**
16
44
  * Adds a named value while preserving repeated keys as arrays.
17
45
  */
@@ -28,4 +56,5 @@ export declare function buildUrl(baseUrl: string, queryString: string): string;
28
56
  * Processes headers and cookies into a headers object
29
57
  */
30
58
  export declare function processHeaders(request: Partial<HarRequest>): Record<string, string>;
59
+ export {};
31
60
  //# sourceMappingURL=http.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/libs/http.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAExD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CAKvG;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,CAAC,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,MAAM,CAO7F;AAED;;GAEG;AACH,eAAO,MAAM,uBAAuB,GAAI,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,MAAM,MAAM,EAAE,OAAO,MAAM,KAAG,IAU9G,CAAA;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,GAAE,UAAU,CAAC,aAAa,CAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAQ1G;AAED;;GAEG;AACH,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAErE;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAqBnF"}
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/libs/http.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAExD,KAAK,UAAU,GAAG;IAChB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AAED,KAAK,aAAa,GAAG;IACnB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AAED,KAAK,qBAAqB,GAAG;IAC3B,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,CAAA;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CAKvG;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,CAAC,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,MAAM,CAO7F;AAED;;GAEG;AACH,eAAO,MAAM,eAAe,GAAI,SAAS,MAAM,KAAG,MAAyC,CAAA;AAE3F;;GAEG;AACH,eAAO,MAAM,YAAY,GAAI,KAAK,MAAM,KAAG,MAgB1C,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,eAAe,GAAI,KAAK,MAAM,EAAE,cAAc,aAAa,EAAE,KAAG,MAY5E,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,cAAc,GAAI,UAAU,qBAAqB,EAAE,EAAE,UAAU,aAAa,EAAE,KAAG,UAAU,EAiBvG,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,uBAAuB,GAAI,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,MAAM,MAAM,EAAE,OAAO,MAAM,KAAG,IAU9G,CAAA;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,GAAE,UAAU,CAAC,aAAa,CAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAQ1G;AAED;;GAEG;AACH,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAErE;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAqBnF"}
package/dist/libs/http.js CHANGED
@@ -17,6 +17,59 @@ export function buildQueryString(queryParams) {
17
17
  const queryPairs = queryParams.map((param) => `${param.name}=${param.value}`);
18
18
  return `?${queryPairs.join('&')}`;
19
19
  }
20
+ /**
21
+ * Normalizes a request method.
22
+ */
23
+ export const normalizeMethod = (method) => (method || 'GET').toUpperCase();
24
+ /**
25
+ * Normalizes URL formatting while preserving origin-only paths.
26
+ */
27
+ export const normalizeUrl = (url) => {
28
+ if (!url) {
29
+ return '';
30
+ }
31
+ try {
32
+ const parsedUrl = new URL(url);
33
+ if (parsedUrl.pathname === '/') {
34
+ return `${parsedUrl.origin}${parsedUrl.search}${parsedUrl.hash}`;
35
+ }
36
+ return parsedUrl.toString();
37
+ }
38
+ catch {
39
+ return url;
40
+ }
41
+ };
42
+ /**
43
+ * Joins URL and query string while preserving existing query values.
44
+ */
45
+ export const joinUrlAndQuery = (url, queryString) => {
46
+ const query = buildQueryString(queryString);
47
+ if (!query) {
48
+ return url;
49
+ }
50
+ if (!url) {
51
+ return query;
52
+ }
53
+ return `${url}${url.includes('?') ? '&' : '?'}${query.slice(1)}`;
54
+ };
55
+ /**
56
+ * Collects deduplicated headers and optional cookie headers.
57
+ */
58
+ export const collectHeaders = (headers, cookies) => {
59
+ const dedupedHeaders = new Map();
60
+ headers?.forEach((header) => {
61
+ if (header.name) {
62
+ dedupedHeaders.set(header.name, header.value ?? '');
63
+ }
64
+ });
65
+ if (cookies?.length) {
66
+ const cookieHeader = cookies
67
+ .map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`)
68
+ .join('; ');
69
+ dedupedHeaders.set('Cookie', cookieHeader);
70
+ }
71
+ return Array.from(dedupedHeaders.entries()).map(([name, value]) => ({ name, value }));
72
+ };
20
73
  /**
21
74
  * Adds a named value while preserving repeated keys as arrays.
22
75
  */
@@ -1 +1 @@
1
- {"version":3,"file":"libcurl.d.ts","sourceRoot":"","sources":["../../../../src/plugins/c/libcurl/libcurl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAA;AAKpD;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,MAQtB,CAAA"}
1
+ {"version":3,"file":"libcurl.d.ts","sourceRoot":"","sources":["../../../../src/plugins/c/libcurl/libcurl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAuB,MAAM,wBAAwB,CAAA;AAsEzE;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,MAqHtB,CAAA"}
@@ -1,5 +1,57 @@
1
- import { libcurl } from '../../../httpsnippet-lite/targets/c/libcurl/client.js';
2
- import { convertWithHttpSnippetLite } from '../../../utils/convertWithHttpSnippetLite.js';
1
+ const normalizeMethod = (method) => (method || 'GET').toUpperCase();
2
+ const escapeCString = (value) => value
3
+ .replaceAll('\\', '\\\\')
4
+ .replaceAll('"', '\\"')
5
+ .replaceAll('\n', '\\n')
6
+ .replaceAll('\r', '\\r')
7
+ .replaceAll('\t', '\\t');
8
+ const normalizeUrl = (url) => {
9
+ if (!url) {
10
+ return '';
11
+ }
12
+ try {
13
+ const parsedUrl = new URL(url);
14
+ const shouldOmitTrailingSlash = parsedUrl.pathname === '/' && !url.endsWith('/') && !url.includes('?') && !url.includes('#');
15
+ const pathname = shouldOmitTrailingSlash ? '' : parsedUrl.pathname;
16
+ return `${parsedUrl.protocol}//${parsedUrl.host}${pathname}${parsedUrl.search}${parsedUrl.hash}`;
17
+ }
18
+ catch {
19
+ return url;
20
+ }
21
+ };
22
+ const buildUrlWithQuery = (url, queryString) => {
23
+ const query = queryString?.length ? queryString.map((param) => `${param.name}=${param.value}`).join('&') : '';
24
+ if (!query) {
25
+ return url;
26
+ }
27
+ if (!url) {
28
+ return `?${query}`;
29
+ }
30
+ return `${url}${url.includes('?') ? '&' : '?'}${query}`;
31
+ };
32
+ const buildCookieString = (cookies) => {
33
+ if (!cookies?.length) {
34
+ return null;
35
+ }
36
+ return cookies.map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`).join('; ');
37
+ };
38
+ const buildFormUrlEncodedBody = (params) => {
39
+ if (!params?.length) {
40
+ return null;
41
+ }
42
+ return params.map((param) => new URLSearchParams([[param.name, param.value ?? '']]).toString()).join('&');
43
+ };
44
+ const formatJsonBody = (text) => {
45
+ if (text === undefined) {
46
+ return '';
47
+ }
48
+ try {
49
+ return JSON.stringify(JSON.parse(text), null, 2);
50
+ }
51
+ catch {
52
+ return text;
53
+ }
54
+ };
3
55
  /**
4
56
  * c/libcurl
5
57
  */
@@ -7,8 +59,96 @@ export const cLibcurl = {
7
59
  target: 'c',
8
60
  client: 'libcurl',
9
61
  title: 'Libcurl',
10
- generate(request) {
11
- // TODO: Write an own converter
12
- return convertWithHttpSnippetLite(libcurl, request);
62
+ generate(request, configuration) {
63
+ if (!request) {
64
+ return '';
65
+ }
66
+ const method = normalizeMethod(request.method);
67
+ const normalizedUrl = normalizeUrl(request.url ?? '');
68
+ const fullUrl = buildUrlWithQuery(normalizedUrl, request.queryString);
69
+ const hasHeaders = Boolean(request.headers?.length);
70
+ const hasCookies = Boolean(request.cookies?.length);
71
+ const body = request.postData;
72
+ const isMultipartBody = body?.mimeType === 'multipart/form-data' && Boolean(body.params?.length);
73
+ const headers = request.headers ?? [];
74
+ const shouldEnableCompression = headers.some((header) => header.name.toLowerCase() === 'accept-encoding' && /gzip|deflate/.test(header.value));
75
+ const lines = [
76
+ '#include <curl/curl.h>',
77
+ '',
78
+ 'int main(void) {',
79
+ ' curl_global_init(CURL_GLOBAL_DEFAULT);',
80
+ ' CURL *curl = curl_easy_init();',
81
+ ' if (!curl) {',
82
+ ' curl_global_cleanup();',
83
+ ' return 1;',
84
+ ' }',
85
+ '',
86
+ ` curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "${escapeCString(method)}");`,
87
+ ` curl_easy_setopt(curl, CURLOPT_URL, "${escapeCString(fullUrl)}");`,
88
+ ];
89
+ if (configuration?.auth?.username && configuration.auth.password) {
90
+ lines.push(` curl_easy_setopt(curl, CURLOPT_USERPWD, "${escapeCString(`${configuration.auth.username}:${configuration.auth.password}`)}");`);
91
+ }
92
+ if (hasHeaders) {
93
+ lines.push('', ' struct curl_slist *headers = NULL;');
94
+ headers.forEach((header) => {
95
+ lines.push(` headers = curl_slist_append(headers, "${escapeCString(`${header.name}: ${header.value}`)}");`);
96
+ });
97
+ lines.push(' curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);');
98
+ }
99
+ if (hasCookies) {
100
+ const cookieString = buildCookieString(request.cookies);
101
+ if (cookieString) {
102
+ lines.push('', ` curl_easy_setopt(curl, CURLOPT_COOKIE, "${escapeCString(cookieString)}");`);
103
+ }
104
+ }
105
+ if (shouldEnableCompression) {
106
+ lines.push('', ' curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "");');
107
+ }
108
+ if (body) {
109
+ if (isMultipartBody && body.params) {
110
+ lines.push('', ' curl_mime *mime = curl_mime_init(curl);');
111
+ body.params.forEach((param) => {
112
+ lines.push('', ' {', ' curl_mimepart *part = curl_mime_addpart(mime);');
113
+ if (param.name) {
114
+ lines.push(` curl_mime_name(part, "${escapeCString(param.name)}");`);
115
+ }
116
+ if (param.fileName !== undefined) {
117
+ lines.push(` curl_mime_filedata(part, "${escapeCString(param.fileName)}");`);
118
+ }
119
+ else {
120
+ lines.push(` curl_mime_data(part, "${escapeCString(param.value ?? '')}", CURL_ZERO_TERMINATED);`);
121
+ }
122
+ if (param.contentType) {
123
+ lines.push(` curl_mime_type(part, "${escapeCString(param.contentType)}");`);
124
+ }
125
+ lines.push(' }');
126
+ });
127
+ lines.push('', ' curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime);');
128
+ }
129
+ else if (body.mimeType === 'application/x-www-form-urlencoded' && body.params?.length) {
130
+ const formBody = buildFormUrlEncodedBody(body.params);
131
+ if (formBody !== null) {
132
+ lines.push('', ` curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "${escapeCString(formBody)}");`);
133
+ }
134
+ }
135
+ else if (body.mimeType === 'application/json' && body.text !== undefined) {
136
+ lines.push('', ` curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "${escapeCString(formatJsonBody(body.text))}");`);
137
+ }
138
+ else if (body.text !== undefined) {
139
+ const fallbackBody = body.mimeType === 'application/octet-stream' ? body.text : formatJsonBody(body.text);
140
+ lines.push('', ` curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "${escapeCString(fallbackBody)}");`);
141
+ }
142
+ }
143
+ lines.push('', ' CURLcode res = curl_easy_perform(curl);');
144
+ lines.push(' curl_easy_cleanup(curl);');
145
+ if (isMultipartBody) {
146
+ lines.push(' curl_mime_free(mime);');
147
+ }
148
+ if (hasHeaders) {
149
+ lines.push(' curl_slist_free_all(headers);');
150
+ }
151
+ lines.push(' curl_global_cleanup();', '', ' return (int)res;', '}');
152
+ return lines.join('\n');
13
153
  },
14
154
  };
@@ -1 +1 @@
1
- {"version":3,"file":"native.d.ts","sourceRoot":"","sources":["../../../../src/plugins/go/native/native.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAA;AAqMpD;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,MAqEtB,CAAA"}
1
+ {"version":3,"file":"native.d.ts","sourceRoot":"","sources":["../../../../src/plugins/go/native/native.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAA;AAwIpD;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,MAqEtB,CAAA"}
@@ -1,4 +1,4 @@
1
- import { buildQueryString } from '../../../libs/http.js';
1
+ import { collectHeaders, joinUrlAndQuery, normalizeMethod, normalizeUrl } from '../../../libs/http.js';
2
2
  const formatImport = (entry) => {
3
3
  if (entry.includes(' ')) {
4
4
  return entry;
@@ -6,47 +6,6 @@ const formatImport = (entry) => {
6
6
  return goString(entry);
7
7
  };
8
8
  const goString = (value) => JSON.stringify(value);
9
- const normalizeMethod = (method) => (method || 'GET').toUpperCase();
10
- const normalizeUrl = (url) => {
11
- if (!url) {
12
- return '';
13
- }
14
- try {
15
- const parsedUrl = new URL(url);
16
- if (parsedUrl.pathname === '/') {
17
- return `${parsedUrl.origin}${parsedUrl.search}${parsedUrl.hash}`;
18
- }
19
- return parsedUrl.toString();
20
- }
21
- catch {
22
- return url;
23
- }
24
- };
25
- const joinUrlAndQuery = (url, queryString) => {
26
- const query = buildQueryString(queryString);
27
- if (!query) {
28
- return url;
29
- }
30
- if (!url) {
31
- return query;
32
- }
33
- return `${url}${url.includes('?') ? '&' : '?'}${query.slice(1)}`;
34
- };
35
- const collectHeaders = (headers, cookies) => {
36
- const dedupedHeaders = new Map();
37
- headers?.forEach((header) => {
38
- if (header.name) {
39
- dedupedHeaders.set(header.name, header.value ?? '');
40
- }
41
- });
42
- if (cookies?.length) {
43
- const cookieHeader = cookies
44
- .map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`)
45
- .join('; ');
46
- dedupedHeaders.set('Cookie', cookieHeader);
47
- }
48
- return Array.from(dedupedHeaders.entries()).map(([name, value]) => ({ name, value }));
49
- };
50
9
  const toPrettyJson = (text) => {
51
10
  if (text === undefined) {
52
11
  return '';
@@ -0,0 +1,6 @@
1
+ import type { Plugin } from '@scalar/types/snippetz';
2
+ /**
3
+ * python/aiohttp
4
+ */
5
+ export declare const pythonAiohttp: Plugin;
6
+ //# sourceMappingURL=aiohttp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aiohttp.d.ts","sourceRoot":"","sources":["../../../../src/plugins/python/aiohttp/aiohttp.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAc,MAAM,EAAE,MAAM,wBAAwB,CAAA;AAyBhE;;GAEG;AACH,eAAO,MAAM,aAAa,EAAE,MA4G3B,CAAA"}
@@ -0,0 +1,107 @@
1
+ import { accumulateRepeatedValue, reduceQueryParams } from '../../../libs/http.js';
2
+ import { LENGTH_CONSIDERED_AS_SHORT, formatPythonValue } from '../../../plugins/python/requestsLike.js';
3
+ const indent = (value, prefix = ' ') => value
4
+ .split('\n')
5
+ .map((line) => (line.trim() === '' ? line : `${prefix}${line}`))
6
+ .join('\n');
7
+ const formatRequestCall = (clientVar, method, url, args) => {
8
+ const urlParam = JSON.stringify(url);
9
+ if (url.length > LENGTH_CONSIDERED_AS_SHORT) {
10
+ return `${clientVar}.${method}(\n ${[urlParam, ...args].join(',\n ')}\n)`;
11
+ }
12
+ if (args.length === 0) {
13
+ return `${clientVar}.${method}(${urlParam})`;
14
+ }
15
+ return `${clientVar}.${method}(${urlParam},\n ${args.join(',\n ')}\n)`;
16
+ };
17
+ /**
18
+ * python/aiohttp
19
+ */
20
+ export const pythonAiohttp = {
21
+ target: 'python',
22
+ client: 'aiohttp',
23
+ title: 'aiohttp',
24
+ generate(request, configuration) {
25
+ const normalizedRequest = {
26
+ url: 'https://example.com',
27
+ method: 'get',
28
+ ...request,
29
+ };
30
+ const method = normalizedRequest.method?.toLowerCase() ?? 'get';
31
+ const requestArgs = [];
32
+ const sessionArgs = [];
33
+ const setupLines = [];
34
+ if (normalizedRequest.headers?.length) {
35
+ const headers = normalizedRequest.headers.reduce((acc, header) => {
36
+ if (!(header.name in acc)) {
37
+ acc[header.name] = header.value;
38
+ }
39
+ return acc;
40
+ }, {});
41
+ requestArgs.push(`headers=${formatPythonValue(headers)}`);
42
+ }
43
+ if (normalizedRequest.queryString?.length) {
44
+ requestArgs.push(`params=${formatPythonValue(reduceQueryParams(normalizedRequest.queryString))}`);
45
+ }
46
+ if (normalizedRequest.cookies?.length) {
47
+ const cookies = Object.fromEntries(normalizedRequest.cookies.map((cookie) => [cookie.name, cookie.value]));
48
+ sessionArgs.push(`cookies=${formatPythonValue(cookies)}`);
49
+ }
50
+ if (configuration?.auth?.username && configuration?.auth?.password) {
51
+ sessionArgs.push(`auth=aiohttp.BasicAuth(${JSON.stringify(configuration.auth.username)}, ${JSON.stringify(configuration.auth.password)})`);
52
+ }
53
+ if (normalizedRequest.postData) {
54
+ const { mimeType, text, params } = normalizedRequest.postData;
55
+ if (mimeType === 'application/json' && text) {
56
+ try {
57
+ requestArgs.push(`json=${formatPythonValue(JSON.parse(text))}`);
58
+ }
59
+ catch {
60
+ requestArgs.push(`data=${JSON.stringify(text)}`);
61
+ }
62
+ }
63
+ else if (mimeType === 'application/octet-stream' && text) {
64
+ requestArgs.push(`data=b"${text}"`);
65
+ }
66
+ else if (mimeType === 'multipart/form-data' && params) {
67
+ setupLines.push('data = aiohttp.FormData()');
68
+ params.forEach((param) => {
69
+ if (param.fileName !== undefined) {
70
+ const addFieldArgs = [
71
+ JSON.stringify(param.name),
72
+ `open(${JSON.stringify(param.fileName)}, "rb")`,
73
+ `filename=${JSON.stringify(param.fileName)}`,
74
+ ];
75
+ if (param.contentType) {
76
+ addFieldArgs.push(`content_type=${JSON.stringify(param.contentType)}`);
77
+ }
78
+ setupLines.push(`data.add_field(${addFieldArgs.join(', ')})`);
79
+ return;
80
+ }
81
+ if (param.contentType) {
82
+ setupLines.push(`data.add_field(${JSON.stringify(param.name)}, ${JSON.stringify(param.value ?? '')}, content_type=${JSON.stringify(param.contentType)})`);
83
+ return;
84
+ }
85
+ setupLines.push(`data.add_field(${JSON.stringify(param.name)}, ${JSON.stringify(param.value ?? '')})`);
86
+ });
87
+ requestArgs.push('data=data');
88
+ }
89
+ else if (mimeType === 'application/x-www-form-urlencoded' && params) {
90
+ const formData = {};
91
+ params.forEach((param) => {
92
+ accumulateRepeatedValue(formData, param.name, param.value ?? '');
93
+ });
94
+ requestArgs.push(`data=${formatPythonValue(formData)}`);
95
+ }
96
+ else if (text) {
97
+ requestArgs.push(`data=${JSON.stringify(text)}`);
98
+ }
99
+ }
100
+ const sessionOpen = sessionArgs.length === 0
101
+ ? 'async with aiohttp.ClientSession() as session:'
102
+ : `async with aiohttp.ClientSession(\n ${sessionArgs.join(',\n ')}\n) as session:`;
103
+ const requestCall = formatRequestCall('await session', method, normalizedRequest.url ?? '', requestArgs);
104
+ const bodyLines = [...setupLines, requestCall];
105
+ return `${sessionOpen}\n${indent(bodyLines.join('\n'))}`;
106
+ },
107
+ };
@@ -0,0 +1,2 @@
1
+ export { pythonAiohttp } from './aiohttp.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/plugins/python/aiohttp/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA"}
@@ -0,0 +1 @@
1
+ export { pythonAiohttp } from './aiohttp.js';
@@ -1 +1 @@
1
- {"version":3,"file":"python3.d.ts","sourceRoot":"","sources":["../../../../src/plugins/python/python3/python3.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAA;AAKpD;;GAEG;AACH,eAAO,MAAM,aAAa,EAAE,MAQ3B,CAAA"}
1
+ {"version":3,"file":"python3.d.ts","sourceRoot":"","sources":["../../../../src/plugins/python/python3/python3.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAc,MAAM,EAAE,MAAM,wBAAwB,CAAA;AA2KhE;;GAEG;AACH,eAAO,MAAM,aAAa,EAAE,MAiF3B,CAAA"}