@powerduck/openapi-request 0.2.2
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/README.md +711 -0
- package/dist/credentials-Cl0G4KpE.d.cts +783 -0
- package/dist/credentials-rqEKODvf.d.ts +783 -0
- package/dist/index-1jRrFc3d.d.cts +215 -0
- package/dist/index-CsRXyS7O.d.ts +215 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +350 -0
- package/dist/index.d.ts +350 -0
- package/dist/index.js +1 -0
- package/dist/protocol-D7sEx8IP.d.ts +62 -0
- package/dist/protocol-Dh-wN2nY.d.cts +62 -0
- package/dist/protocols/graphql/index.cjs +1 -0
- package/dist/protocols/graphql/index.d.cts +95 -0
- package/dist/protocols/graphql/index.d.ts +95 -0
- package/dist/protocols/graphql/index.js +1 -0
- package/dist/protocols/grpc/index.cjs +1 -0
- package/dist/protocols/grpc/index.d.cts +61 -0
- package/dist/protocols/grpc/index.d.ts +61 -0
- package/dist/protocols/grpc/index.js +1 -0
- package/dist/protocols/http/index.cjs +1 -0
- package/dist/protocols/http/index.d.cts +161 -0
- package/dist/protocols/http/index.d.ts +161 -0
- package/dist/protocols/http/index.js +1 -0
- package/dist/protocols/mcp/index.cjs +1 -0
- package/dist/protocols/mcp/index.d.cts +3 -0
- package/dist/protocols/mcp/index.d.ts +3 -0
- package/dist/protocols/mcp/index.js +1 -0
- package/dist/protocols/ws/index.cjs +1 -0
- package/dist/protocols/ws/index.d.cts +35 -0
- package/dist/protocols/ws/index.d.ts +35 -0
- package/dist/protocols/ws/index.js +1 -0
- package/dist/types-C9ifzKqk.d.cts +1226 -0
- package/dist/types-C9ifzKqk.d.ts +1226 -0
- package/package.json +93 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { O as OperationTarget, a as SendOptions, E as ExecResult } from './types-C9ifzKqk.js';
|
|
2
|
+
|
|
3
|
+
interface LocatedOperation {
|
|
4
|
+
path: string;
|
|
5
|
+
/** Lower-cased method name; custom verbs come from `additionalOperations`. */
|
|
6
|
+
method: string;
|
|
7
|
+
/** True when the method came from `additionalOperations`. */
|
|
8
|
+
isCustomMethod: boolean;
|
|
9
|
+
/** The key used inside `additionalOperations`, preserving its original case. */
|
|
10
|
+
customMethodKey?: string;
|
|
11
|
+
/** Fully dereferenced Operation Object. */
|
|
12
|
+
operation: any;
|
|
13
|
+
pathItem: any;
|
|
14
|
+
/** Path-level and operation-level parameters merged, operation wins. */
|
|
15
|
+
parameters: any[];
|
|
16
|
+
/** Effective servers, honoring operation > pathItem > document precedence. */
|
|
17
|
+
servers: any[];
|
|
18
|
+
security?: any[];
|
|
19
|
+
}
|
|
20
|
+
declare function locateOperation(spec: any, target: OperationTarget): LocatedOperation;
|
|
21
|
+
|
|
22
|
+
interface AdapterContext {
|
|
23
|
+
spec: any;
|
|
24
|
+
options: SendOptions;
|
|
25
|
+
located: LocatedOperation;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Extra runtime facilities handed to `execute()`.
|
|
29
|
+
* Optional so existing adapters keep compiling, but new adapters should honor
|
|
30
|
+
* `signal` so long-lived streams can be cancelled deterministically.
|
|
31
|
+
*/
|
|
32
|
+
interface ExecuteContext {
|
|
33
|
+
/**
|
|
34
|
+
* Aborted when the caller wants execution to stop. Adapters must tear down
|
|
35
|
+
* sockets and settle their promise promptly, resolving with whatever has been
|
|
36
|
+
* collected so far rather than rejecting.
|
|
37
|
+
*/
|
|
38
|
+
signal?: AbortSignal;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Every protocol implements this contract. `plan()` must be pure and
|
|
42
|
+
* synchronous so callers can inspect or export the plan without side effects.
|
|
43
|
+
*/
|
|
44
|
+
interface ProtocolAdapter<TPlan = unknown> {
|
|
45
|
+
readonly name: string;
|
|
46
|
+
/**
|
|
47
|
+
* Return 0 (or any non-positive / non-finite value) when unsupported;
|
|
48
|
+
* higher finite numbers win the resolution race. Must not throw — a throwing
|
|
49
|
+
* adapter is treated as "unsupported".
|
|
50
|
+
*/
|
|
51
|
+
supports(ctx: AdapterContext): number;
|
|
52
|
+
plan(ctx: AdapterContext): TPlan;
|
|
53
|
+
/**
|
|
54
|
+
* Perform the call. Must always resolve for protocol-level failures and
|
|
55
|
+
* report them via `ExecResult.error`; reject only for programming errors.
|
|
56
|
+
*/
|
|
57
|
+
execute(plan: TPlan, options: SendOptions, ctx?: ExecuteContext): Promise<ExecResult>;
|
|
58
|
+
/** Optional cleanup for adapters holding process-wide resources. */
|
|
59
|
+
dispose?(): void | Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export { type AdapterContext as A, type ExecuteContext as E, type LocatedOperation as L, type ProtocolAdapter as P, locateOperation as l };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { O as OperationTarget, a as SendOptions, E as ExecResult } from './types-C9ifzKqk.cjs';
|
|
2
|
+
|
|
3
|
+
interface LocatedOperation {
|
|
4
|
+
path: string;
|
|
5
|
+
/** Lower-cased method name; custom verbs come from `additionalOperations`. */
|
|
6
|
+
method: string;
|
|
7
|
+
/** True when the method came from `additionalOperations`. */
|
|
8
|
+
isCustomMethod: boolean;
|
|
9
|
+
/** The key used inside `additionalOperations`, preserving its original case. */
|
|
10
|
+
customMethodKey?: string;
|
|
11
|
+
/** Fully dereferenced Operation Object. */
|
|
12
|
+
operation: any;
|
|
13
|
+
pathItem: any;
|
|
14
|
+
/** Path-level and operation-level parameters merged, operation wins. */
|
|
15
|
+
parameters: any[];
|
|
16
|
+
/** Effective servers, honoring operation > pathItem > document precedence. */
|
|
17
|
+
servers: any[];
|
|
18
|
+
security?: any[];
|
|
19
|
+
}
|
|
20
|
+
declare function locateOperation(spec: any, target: OperationTarget): LocatedOperation;
|
|
21
|
+
|
|
22
|
+
interface AdapterContext {
|
|
23
|
+
spec: any;
|
|
24
|
+
options: SendOptions;
|
|
25
|
+
located: LocatedOperation;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Extra runtime facilities handed to `execute()`.
|
|
29
|
+
* Optional so existing adapters keep compiling, but new adapters should honor
|
|
30
|
+
* `signal` so long-lived streams can be cancelled deterministically.
|
|
31
|
+
*/
|
|
32
|
+
interface ExecuteContext {
|
|
33
|
+
/**
|
|
34
|
+
* Aborted when the caller wants execution to stop. Adapters must tear down
|
|
35
|
+
* sockets and settle their promise promptly, resolving with whatever has been
|
|
36
|
+
* collected so far rather than rejecting.
|
|
37
|
+
*/
|
|
38
|
+
signal?: AbortSignal;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Every protocol implements this contract. `plan()` must be pure and
|
|
42
|
+
* synchronous so callers can inspect or export the plan without side effects.
|
|
43
|
+
*/
|
|
44
|
+
interface ProtocolAdapter<TPlan = unknown> {
|
|
45
|
+
readonly name: string;
|
|
46
|
+
/**
|
|
47
|
+
* Return 0 (or any non-positive / non-finite value) when unsupported;
|
|
48
|
+
* higher finite numbers win the resolution race. Must not throw — a throwing
|
|
49
|
+
* adapter is treated as "unsupported".
|
|
50
|
+
*/
|
|
51
|
+
supports(ctx: AdapterContext): number;
|
|
52
|
+
plan(ctx: AdapterContext): TPlan;
|
|
53
|
+
/**
|
|
54
|
+
* Perform the call. Must always resolve for protocol-level failures and
|
|
55
|
+
* report them via `ExecResult.error`; reject only for programming errors.
|
|
56
|
+
*/
|
|
57
|
+
execute(plan: TPlan, options: SendOptions, ctx?: ExecuteContext): Promise<ExecResult>;
|
|
58
|
+
/** Optional cleanup for adapters holding process-wide resources. */
|
|
59
|
+
dispose?(): void | Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export { type AdapterContext as A, type ExecuteContext as E, type LocatedOperation as L, type ProtocolAdapter as P, locateOperation as l };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,i={};((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(i,{GraphQLAdapter:()=>se,INTROSPECTION_QUERY:()=>H,discoverAndWriteGraphQLSchema:()=>ie,generateAllOperations:()=>te,generateOperation:()=>ee,introspectSchema:()=>z,resolveGraphQLConfig:()=>C,runGraphQL:()=>F,writeGraphQLOperations:()=>oe}),module.exports=(e=i,((e,i,s,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let u of n(i))o.call(e,u)||u===s||t(e,u,{get:()=>i[u],enumerable:!(a=r(i,u))||a.enumerable});return e})(t({},"__esModule",{value:!0}),e));var s=Symbol.for("@powerduck/openapi-request.ProtoKitError"),a=class e extends Error{code;details;[s]=!0;constructor(t,r,n,o){if(super(t),this.name="ProtoKitError",this.code="string"==typeof r&&r?r:"UNKNOWN",this.details=n,o&&"cause"in o)try{Object.defineProperty(this,"cause",{value:o.cause,configurable:!0,writable:!0,enumerable:!1})}catch{}Object.setPrototypeOf(this,e.prototype),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}static isProtoKitError(e){return"object"==typeof e&&null!==e&&!0===e[s]}toJSON(){return{name:this.name,code:this.code,message:this.message,...void 0===this.details?{}:{details:this.details}}}};function u(e,t,r,n){return new a(t,e,r,n)}function c(e){const t=typeof e;if(null===e)return"null";if("undefined"===t)return"undefined";if("function"===t){const t=e.name;return t?`[Function: ${t}]`:"[Function (anonymous)]"}if("symbol"===t)return String(e);if("bigint"===t)return`${String(e)}n`;try{const t=JSON.stringify(e);if("string"==typeof t)return t}catch{}try{return String(e)}catch{return"[unserializable value]"}}function l(e){if(a.isProtoKitError(e))return{message:e.message||"Unknown ProtoKitError",code:e.code,name:e.name};if(e instanceof Error){const t=e.code,r="string"==typeof t||"number"==typeof t?String(t):void 0;return{message:e.message||e.name||"Unknown error",...r?{code:r}:{},name:e.name||"Error"}}if("object"==typeof e&&null!==e&&"string"==typeof e.message){const t=e,r="string"==typeof t.code||"number"==typeof t.code?String(t.code):void 0;return{message:t.message||"Unknown error",...r?{code:r}:{},..."string"==typeof t.name?{name:t.name}:{}}}return"string"==typeof e?{message:e||"Unknown error"}:{message:c(e)}}var p=new Set(["__proto__","constructor","prototype"]);function f(e){return p.has(e)}function d(e){if(null===e||"object"!=typeof e)return e;if("function"==typeof globalThis.structuredClone)try{return globalThis.structuredClone(e)}catch{}return function(e){return h(e,new Set)}(e)}function h(e,t){if(null===e)return null;const r=typeof e;if("string"===r||"boolean"===r)return e;if("number"===r)return Number.isFinite(e)?e:null;if("bigint"===r)return e.toString();if("object"!==r)return;const n=e;if(t.has(n))return null;const o=n.toJSON;if("function"==typeof o){let e;try{e=o.call(n)}catch{return null}return e===n?null:h(e,t)}t.add(n);try{if(Array.isArray(n)){const e=new Array(n.length);for(let r=0;r<n.length;r+=1){const o=h(n[r],t);e[r]=void 0===o?null:o}return e}const e={};for(const r of Object.keys(n)){if(f(r))continue;let o;try{o=n[r]}catch{continue}const i=h(o,t);void 0!==i&&(e[r]=i)}return e}finally{t.delete(n)}}function m(e,t){const r=y(e);return r&&-1!==r.indexOf("{{")&&t?r.replace(/\{\{\s*([\w.$-]+)\s*\}\}/g,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;const n=t[r];return null==n?e:y(n)}):r}function y(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:""}catch{try{return String(e)}catch{return""}}}function b(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}var v=/(token|secret|password|passwd|apikey|api_key|credential|private|authorization)/i;function g(e){return v.test(e)}var A="\0PK_OPEN\0",E="\0PK_CLOSE\0";function O(e,t){const r="string"==typeof t.serverUrl?t.serverUrl.trim():"";if(r)return x(T(r),"options.serverUrl");const n=Array.isArray(e)?e.filter(b):[],o=n[Number.isInteger(t.serverIndex)?Math.max(0,t.serverIndex):0]??n[0];let i=o&&"string"==typeof o.url&&o.url.trim()?o.url.trim():"";if(!i)throw u("NO_SERVER_URL","The document declares no usable server URL. Pass options.serverUrl to specify one.");return i=function(e,t,r){const n=b(t)?t:{};let o=e;for(const[e,t]of Object.entries(n)){const n=r?.[e];let i;if(null!=n){if(i=n,Array.isArray(t?.enum)&&t.enum.length&&!t.enum.some(e=>String(e)===String(n)))throw u("BAD_SERVER_VARIABLE",`Server variable "${e}" must be one of: ${t.enum.join(", ")}`,{provided:n,allowed:t.enum})}else if(void 0!==t?.default)i=t.default;else{if(!Array.isArray(t?.enum)||!t.enum.length)throw u("BAD_SERVER_VARIABLE",`Server variable "${e}" has no default; pass serverVariables["${e}"].`);i=t.enum[0]}o=o.split(`{${e}}`).join(String(i??""))}for(const[e,t]of Object.entries(r??{}))Object.prototype.hasOwnProperty.call(n,e)||null!=t&&(o=o.split(`{${e}}`).join(String(t)));return o}(i,o?.variables,t.serverVariables),x(T(i),"spec.servers")}function T(e){return e.replace(/\/+$/,"")||e}function x(e,t){const r=function(e){return-1===e.indexOf("{")?e:e.split("{{").join(A).split("}}").join(E).replace(/\{[^{}]*\}/g,"").split(A).join("{{").split(E).join("}}")}(e);if(!r)throw u("BAD_SERVER_URL",`${t} resolved to an empty URL`);if(r.includes("{{"))return r;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(r))throw u("RELATIVE_SERVER_URL",`${t} resolved to the relative URL "${r}". A request needs an absolute origin; pass options.serverUrl.`,{url:r});return r}var w=new Set(["__proto__","constructor","prototype"]),S="2024-01-01T00:00:00.000Z",_=12,N=2,j=5,q=256;function $(e,t=0,r={}){const n=r.maxDepth??_;if(!e||"object"!=typeof e||Array.isArray(e))return null;if(t>n)return null;if("string"==typeof e.$ref)return null;if(void 0!==e.example)return e.example;const o=function(e){if(null==e)return;if(Array.isArray(e))return e.length?e[0]:void 0;if("object"==typeof e)for(const t of Object.values(e))if(void 0!==t){if(t&&"object"==typeof t){if("value"in t)return t.value;if("externalValue"in t)continue}return t}return}(e.examples);if(void 0!==o)return o;if(void 0!==e.default)return e.default;if(void 0!==e.const)return e.const;if(Array.isArray(e.enum)&&e.enum.length){const t=e.enum.find(e=>null!==e);return void 0!==t?t:e.enum[0]}if(Array.isArray(e.allOf)&&e.allOf.length)return function(e,t,r){let n,o;for(const i of e.allOf){const e=$(i,t+1,r);null===e||"object"!=typeof e||Array.isArray(e)?null!=e&&(o=e):n={...n??{},...e}}if(e.properties||e.required){const o=k(e,t,r);o&&"object"==typeof o&&(n={...n??{},...o})}return n||(void 0!==o?o:{})}(e,t,r);for(const n of["oneOf","anyOf"]){const o=e[n];if(Array.isArray(o)&&o.length){return $(o.find(e=>e&&"object"==typeof e&&"null"!==e.type)??o[0],t+1,r)}}const i=function(e){const t=Array.isArray(e.type)?e.type.find(e=>"string"==typeof e&&"null"!==e)??(e.type.includes("null")?"null":void 0):"string"==typeof e.type?e.type:void 0;if(t)return t;if(e.properties||e.additionalProperties||e.required)return"object";if(e.items||e.prefixItems)return"array";if(void 0!==e.minimum||void 0!==e.maximum||void 0!==e.multipleOf)return"number";return"string"}(e);switch(i){case"object":return k(e,t,r);case"array":return function(e,t,r){const n=[];if(Array.isArray(e.prefixItems))for(const o of e.prefixItems)n.push($(o,t+1,r));const o=R(e.minItems)??1,i=R(e.maxItems);let s=Math.max(o,n.length,1);s=Math.min(s,j),void 0!==i&&(s=Math.min(s,Math.max(i,0)));const a=e.items&&"object"==typeof e.items?e.items:void 0;if(!a&&Array.isArray(e.prefixItems))return n.slice(0,0===s?0:Math.max(s,n.length));for(;n.length<s;){const o=$(a??{},t+1,r);if(!0===e.uniqueItems&&n.length>0)break;n.push(o)}return void 0!==i?n.slice(0,Math.max(i,0)):n}(e,t,r);case"integer":return function(e){const{min:t,max:r}=I(e,!0);let n=0;void 0!==t&&n<t&&(n=Math.ceil(t));void 0!==r&&n>r&&(n=Math.floor(r));const o=L(e.multipleOf);if(void 0!==o&&o>0){const e=Math.ceil(n/o)*o;(void 0===r||e<=r)&&(n=e)}return Math.trunc(n)}(e);case"number":return function(e){const{min:t,max:r}=I(e,!1);let n=0;void 0!==t&&n<t&&(n=t);void 0!==r&&n>r&&(n=r);const o=L(e.multipleOf);if(void 0!==o&&o>0){const e=Math.ceil(n/o)*o;(void 0===r||e<=r)&&(n=e)}return n}(e);case"boolean":return!1;case"null":return null;default:return function(e){const t="string"==typeof e.format?e.format:void 0,r=t?function(e){switch(e){case"date-time":return S;case"date":return S.slice(0,10);case"time":return S.slice(11,19);case"duration":return"PT1S";case"uuid":return"00000000-0000-4000-8000-000000000000";case"email":case"idn-email":return"user@example.com";case"hostname":case"idn-hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"uri":case"url":case"iri":return"https://example.com";case"uri-reference":case"iri-reference":case"json-pointer":return"/example";case"uri-template":return"https://example.com/{id}";case"relative-json-pointer":return"0/example";case"regex":return"^example$";case"byte":return"ZXhhbXBsZQ==";case"binary":return"";case"password":return"password";default:return}}(t):void 0;return void 0!==r?P(r,e):"string"==typeof e.pattern&&e.pattern.length?"":P("string",e)}(e)}}function k(e,t,r){const n={},o=Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[],i=e.properties&&"object"==typeof e.properties?e.properties:{},s=!0===r.includeReadOnly,a=!1!==r.includeWriteOnly;for(const[e,u]of Object.entries(i))w.has(e)||!s&&u&&!0===u.readOnly||!a&&u&&!0===u.writeOnly||t>N&&o.length&&!o.includes(e)||(n[e]=$(u,t+1,r));for(const e of o)w.has(e)||e in n||(n[e]=$(i[e]??{},t+1,r));!Object.keys(n).length&&e.additionalProperties&&"object"==typeof e.additionalProperties&&(n.key=$(e.additionalProperties,t+1,r));const u=R(e.minProperties);if(void 0!==u){const o=e.additionalProperties&&"object"==typeof e.additionalProperties?e.additionalProperties:{};let i=1;for(;Object.keys(n).length<Math.min(u,20);){const e=`additionalProp${i}`;i+=1,e in n||(n[e]=$(o,t+1,r))}}return n}function I(e,t){const r=t?1:Number.EPSILON>0?1e-6:1;let n=L(e.minimum),o=L(e.maximum);const i=e.exclusiveMinimum,s=e.exclusiveMaximum;if("number"==typeof i&&Number.isFinite(i)){const e=i+r;n=void 0===n?e:Math.max(n,e)}else!0===i&&void 0!==n&&(n+=r);if("number"==typeof s&&Number.isFinite(s)){const e=s-r;o=void 0===o?e:Math.min(o,e)}else!0===s&&void 0!==o&&(o-=r);return{min:n,max:o}}function P(e,t){const r=R(t.minLength),n=R(t.maxLength);let o=e;return void 0!==r&&o.length<r&&(o=o.padEnd(Math.min(r,q),"x")),void 0!==n&&o.length>n&&(o=o.slice(0,Math.max(n,0))),o}function L(e){if("number"==typeof e&&Number.isFinite(e))return e}function R(e){const t=L(e);if(void 0===t)return;const r=Math.floor(t);return r<0?0:r}function C(e,t,r){const n=r.graphql??{},o=e.operation?.["x-graphql"],i=o&&"object"==typeof o?o:{},s={...r.variables??{}};let a;if(a=n.endpoint?n.endpoint:"string"==typeof i.endpoint&&i.endpoint?i.endpoint:O(e.servers,r),a=m(a,s),/\{\{[^}]+\}\}/.test(a))throw u("BAD_GRAPHQL_ENDPOINT",`Unresolved variable in GraphQL endpoint: ${a}`);try{const e=new URL(a);if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error("not http(s)")}catch{throw u("BAD_GRAPHQL_ENDPOINT",`GraphQL endpoint must be an absolute http(s) URL, received: ${a}`)}const c=n.query??i.query;if("string"!=typeof c||!c.trim())throw u("BAD_GRAPHQL_QUERY","No GraphQL query/mutation document was found. Provide options.graphql.query or declare it on the operation as x-graphql.query (see writeGraphQLOperations).");const l=n.operationName??("string"==typeof(p=i.operationName)&&p.length?p:void 0);var p;const f=b(i.variablesSchema)?$(i.variablesSchema):void 0,d=b(i.variables)?i.variables:void 0,h=b(r.values?.body)?r.values.body:void 0,y={...b(f)?f:{},...d??{},...h??{},...n.variables??{}},v={},g=e=>{if(b(e))for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&(v[t]=m(String(r),s))};g(r.values?.header),g(i.headers),g(n.headers),D(v,"content-type")||n.useGet||(v["Content-Type"]="application/json"),D(v,"accept")||(v.Accept="application/json, text/event-stream");const A=r.auth;if(A&&"none"!==A.type&&!D(v,"authorization"))if("bearer"===A.type)v.Authorization=`Bearer ${A.token??""}`;else if("basic"===A.type){const e=`${A.username??""}:${A.password??""}`;v.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===A.type&&"header"===(A.in??"header")&&(v[A.key??"X-API-Key"]=A.value??"");return{endpoint:a,query:c,operationName:l,variables:y,headers:v,useGet:!0===n.useGet}}function D(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t)}var G=new Set(["[DONE]","DONE","[done]","done"]),B=/\r\n\r\n|\n\n|\r\r/,M=/^\d+$/;function U(e,t){const r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.floor(r):t}var Q=class{buffer="";decoder=new TextDecoder("utf-8");lastEventId;bomChecked=!1;overflowed=!1;sequence=0;maxBufferChars;maxEventChars;inheritEventId;droppedEvents=0;constructor(e={}){this.maxBufferChars=U(e.maxBufferChars,4194304),this.maxEventChars=U(e.maxEventChars,1048576),this.inheritEventId=!1!==e.inheritEventId}get truncated(){return this.overflowed}get count(){return this.sequence}push(e){if(null==e)return[];if("string"==typeof e)this.buffer+=e;else{let t;if(e instanceof Uint8Array)t=e;else try{t=new Uint8Array(e)}catch{return[]}try{this.buffer+=this.decoder.decode(t,{stream:!0})}catch{return[]}}!this.bomChecked&&this.buffer.length&&(this.bomChecked=!0,65279===this.buffer.charCodeAt(0)&&(this.buffer=this.buffer.slice(1)));const t=this.drain();return this.buffer.length>this.maxBufferChars&&(this.overflowed=!0,this.droppedEvents+=1,this.buffer=this.buffer.slice(-8)),t}flush(){try{this.buffer+=this.decoder.decode()}catch{}const e=this.drain(),t=this.buffer;if(this.buffer="",t.trim()){const r=this.parseBlock(t);r&&e.push(r)}return e}reset(){this.buffer="",this.lastEventId=void 0,this.bomChecked=!1,this.overflowed=!1,this.sequence=0,this.droppedEvents=0;try{this.decoder.decode()}catch{}}drain(){const e=[];for(;;){const t=B.exec(this.buffer);if(!t)break;const r=this.buffer.slice(0,t.index);this.buffer=this.buffer.slice(t.index+t[0].length);const n=this.parseBlock(r);n&&e.push(n)}return e}parseBlock(e){const t=e.split(/\r\n|\n|\r/),r=[],n={data:"",receivedAt:Date.now(),direction:"in"};let o=!1,i=0,s=!1;for(const e of t){if(""===e)continue;if(58===e.charCodeAt(0))continue;const t=e.indexOf(":"),a=-1===t?e:e.slice(0,t);let u=-1===t?"":e.slice(t+1);switch(32===u.charCodeAt(0)&&(u=u.slice(1)),a){case"data":{if(o=!0,s)break;const e=this.maxEventChars-i;u.length>e?(r.push(u.slice(0,Math.max(0,e))),s=!0,this.overflowed=!0,this.droppedEvents+=1):(r.push(u),i+=u.length+1);break}case"event":n.event=u,o=!0;break;case"id":u.includes("\0")||(n.id=u,this.lastEventId=u),o=!0;break;case"retry":if(M.test(u)&&u.length<=15){const e=Number(u);Number.isSafeInteger(e)&&(n.retry=e)}o=!0}}if(!o)return null;if(n.data=r.join("\n"),void 0===n.id&&this.inheritEventId&&void 0!==this.lastEventId&&(n.id=this.lastEventId),!s){const e=n.data.trim();if(e&&!G.has(e)&&function(e){const t=e.charCodeAt(0);return 123===t||91===t||34===t}(e))try{n.parsed=JSON.parse(n.data)}catch{}}return this.sequence+=1,n}};function V(e){const t={};return e.forEach((e,r)=>{t[r]=t[r]?`${t[r]}, ${e}`:e}),t}async function F(e,t,r){const n=Date.now(),o=r?.signal??t.signal,i=e.useGet?function(e){const t=new URL(e.endpoint);return t.searchParams.set("query",e.query),e.operationName&&t.searchParams.set("operationName",e.operationName),Object.keys(e.variables).length&&t.searchParams.set("variables",JSON.stringify(e.variables)),t.toString()}(e):e.endpoint,s=e.useGet?void 0:JSON.stringify({query:e.query,variables:e.variables,...e.operationName?{operationName:e.operationName}:{}}),a="number"==typeof t.timeout&&t.timeout>0?t.timeout:3e4,u=new AbortController,c=()=>u.abort();o?.addEventListener("abort",c,{once:!0});const p=setTimeout(()=>u.abort(),a);let f;p.unref?.();try{f=await fetch(i,{method:e.useGet?"GET":"POST",headers:e.headers,body:s,signal:u.signal})}catch(t){clearTimeout(p),o?.removeEventListener("abort",c);const r=Date.now(),a=!0===o?.aborted;return{protocol:"http",request:{method:e.useGet?"GET":"POST",url:i,headers:e.headers,body:s},response:{status:0,statusText:a?"Aborted":"Request failed",headers:{},timings:{startedAt:n,endedAt:r,durationMs:r-n},sizeBytes:0},error:a?{message:"GraphQL request aborted",code:"ABORTED"}:l(t)}}const d=Date.now(),h=f.headers.get("content-type")??void 0,m=!!h&&/text\/event-stream/i.test(h);let y,b,v,g,A=0;try{if(m&&f.body){const e=new Q({maxBufferChars:t.maxBufferChars,maxEventChars:t.maxEventChars,inheritEventId:t.inheritEventId});v=[];const r="number"==typeof t.maxEvents&&t.maxEvents>0?t.maxEvents:100,n=f.body.getReader();for(;;){const{done:t,value:o}=await n.read();if(t)break;A+=o?.byteLength??0;for(const t of e.push(o))if(v.push(t),v.length>=r)break;if(v.length>=r){try{await n.cancel()}catch{}break}}for(const t of e.flush())v.length<r&&v.push(t)}else{const e=await f.text();if(A=e.length,b=e,h&&/json/i.test(h)&&e.trim())try{y=JSON.parse(e)}catch{}}}catch(e){g=l(e)}finally{clearTimeout(p),o?.removeEventListener("abort",c)}const E=Date.now();if(!g&&!m&&J(y)){const e=void 0!==y.data&&null!==y.data,t=Array.isArray(y.errors)?y.errors:void 0;!e&&t?.length&&(g={message:t.map(e=>e?.message).filter(Boolean).join("; ")||"GraphQL request returned errors",code:"GRAPHQL_ERRORS"})}return g||f.ok||J(y)||(g={message:`GraphQL endpoint responded HTTP ${f.status}`,code:String(f.status)}),{protocol:"http",request:{method:e.useGet?"GET":"POST",url:i,headers:e.headers,body:e.useGet?void 0:{query:e.query,variables:e.variables,operationName:e.operationName}},response:{status:f.status,statusText:f.statusText,headers:V(f.headers),contentType:h,...m?{events:v}:{body:y,text:b},timings:{startedAt:n,endedAt:E,durationMs:E-n,firstByteMs:d-n},sizeBytes:A},...g?{error:g}:{}}}function J(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var H="\nquery IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types { ...FullType }\n }\n}\nfragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args { ...InputValue }\n type { ...TypeRef }\n isDeprecated\n deprecationReason\n }\n inputFields { ...InputValue }\n enumValues(includeDeprecated: true) { name description isDeprecated deprecationReason }\n}\nfragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n}\nfragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType { kind name }\n }\n }\n }\n }\n }\n}\n".trim();async function z(e,t={}){let r,n;try{r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...t.headers??{}},body:JSON.stringify({operationName:"IntrospectionQuery",query:H}),signal:t.signal})}catch(e){throw u("GRAPHQL_INTROSPECTION_FAILED",`Could not reach GraphQL endpoint for introspection: ${e?.message??e}`,void 0,{cause:e})}try{n=await r.json()}catch(e){throw u("GRAPHQL_INTROSPECTION_FAILED",`Introspection response was not valid JSON (HTTP ${r.status})`,void 0,{cause:e})}if(!r.ok||!n?.data?.__schema){throw u("GRAPHQL_INTROSPECTION_FAILED",`Introspection failed: ${Array.isArray(n?.errors)&&n.errors.length?n.errors.map(e=>e?.message).filter(Boolean).join("; "):`HTTP ${r.status}`}. The server may have introspection disabled.`)}const o=n.data.__schema,i=new Map;for(const e of o.types??[])e?.name&&"string"==typeof e.name&&(e.name.startsWith("__")||i.set(e.name,e));return{schema:{queryType:o.queryType?.name??void 0,mutationType:o.mutationType?.name??void 0,subscriptionType:o.subscriptionType?.name??void 0,types:i},raw:o}}function K(e){let t=e,r=!0,n=0,o=!1;for(;t;)if("NON_NULL"!==t.kind){if("LIST"!==t.kind)return 0===n&&(r=!o),{named:t.name??void 0,nullable:r,listDepth:n};n+=1,r=!o,o=!1,t=t.ofType??null}else o=!0,t=t.ofType??null;return{nullable:!0,listDepth:n}}var W={ID:{type:"string"},String:{type:"string"},Int:{type:"integer"},Float:{type:"number"},Boolean:{type:"boolean"}};function X(e,t,r){const{named:n,nullable:o,listDepth:i}=K(e.type);let s;const a=n?t.types.get(n):void 0;if(n&&W[n])s={...W[n]};else if("ENUM"===a?.kind)s={type:"string",enum:(a.enumValues??[]).map(e=>e.name)};else if("INPUT_OBJECT"===a?.kind){const e={},n=[];for(const o of a.inputFields??[]){e[o.name]=X(o,t,r);K(o.type).nullable||null!=o.defaultValue||n.push(o.name)}s={type:"object",properties:e,...n.length?{required:n}:{}}}else n&&!W[n]&&r.push(`Argument "${e.name}" has custom scalar type "${n}"; sampled as a string.`),s={type:"string"};for(let e=0;e<i;e+=1)s={type:"array",items:s};return o&&(s.nullable=!0),s}var Z=2;function Y(e,t,r,n){if(!e)return"__typename";const o=t.types.get(e);if(!o||!Array.isArray(o.fields)||!o.fields.length)return"__typename";if(n.has(e)||r<=0)return"__typename";n.add(e);const i=[];for(const e of o.fields){if(e.isDeprecated)continue;if((e.args??[]).some(e=>!K(e.type).nullable))continue;const{named:o,listDepth:s}=K(e.type),a=o?t.types.get(o):void 0;if(!a||"SCALAR"===a.kind||"ENUM"===a.kind||!!W[o??""])i.push(e.name);else if("OBJECT"===a?.kind||"INTERFACE"===a?.kind||"UNION"===a?.kind){if(r<=1)continue;const s=Y(o,t,r-1,new Set(n));i.push(`${e.name} { ${s} }`)}if(i.length>=12)break}return i.length?i.join(" "):"__typename"}function ee(e,t,r){const n=[],o={},i=[],s=[],a=[];for(const e of t.args??[]){const{named:t,nullable:u,listDepth:c}=K(e.type);let l=t??"String";for(let e=0;e<c;e+=1)l=`[${l}]`;u||(l+="!"),s.push(`$${e.name}: ${l}`),a.push(`${e.name}: $${e.name}`),o[e.name]=X(e,r,n),u||null!=e.defaultValue||i.push(e.name)}const{named:u,listDepth:c}=K(t.type),l=u?r.types.get(u):void 0,p=l&&("OBJECT"===l.kind||"INTERFACE"===l.kind||"UNION"===l.kind)?` { ${Y(u,r,Z,new Set)} }`:"",f=`${re(e)}_${re(t.name)}`,d=s.length?`(${s.join(", ")})`:"",h=a.length?`(${a.join(", ")})`:"",m=`${e} ${f}${d} {\n ${t.name}${h}${p}\n}`;return{operationType:e,fieldName:t.name,operationName:f,query:m,variablesSchema:{type:"object",properties:o,required:i},notes:n}}function te(e){const t=[],r=[[e.queryType,"query"],[e.mutationType,"mutation"],[e.subscriptionType,"subscription"]];for(const[n,o]of r){if(!n)continue;const r=e.types.get(n);for(const n of r?.fields??[])t.push(ee(o,n,e))}return t}function re(e){return e?e[0].toUpperCase()+e.slice(1):e}function ne(e){return`/graphql/${e.operationType}/${e.fieldName}`}function oe(e,t,r,n={}){if(!e||"object"!=typeof e||Array.isArray(e))throw u("BAD_SPEC","spec must be an object");const o=!1!==n.overwrite,i=d(e);b(i.paths)||(i.paths={});for(const e of r){const r=ne(e);!o&&b(i.paths[r])||(i.paths[r]={post:{operationId:`graphql_${e.operationType}_${e.fieldName}`,summary:`GraphQL ${e.operationType}: ${e.fieldName}`,"x-protocol":"graphql","x-graphql":{endpoint:t,operationType:e.operationType,operationName:e.operationName,query:e.query,variablesSchema:e.variablesSchema},requestBody:{required:e.variablesSchema.required.length>0,content:{"application/json":{schema:{type:"object",properties:e.variablesSchema.properties,required:e.variablesSchema.required}}}},responses:{200:{description:"GraphQL response envelope (data/errors)."}},...e.notes.length?{"x-graphql-notes":e.notes}:{}}})}return i}async function ie(e,t,r={}){const{schema:n}=await z(t,{headers:r.headers,signal:r.signal}),o=te(n),i=o.flatMap(e=>e.notes.map(t=>`${e.operationType} ${e.fieldName}: ${t}`));o.length||i.push("Introspection succeeded but the schema declares no query, mutation or subscription fields.");return{spec:oe(e,t,o,r),operations:o,warnings:i}}var se=class{name="graphql";supports(e){const t=e.located.operation??{};return"graphql"===t["x-protocol"]?20:(r=t["x-graphql"])&&"object"==typeof r&&!Array.isArray(r)||e.options.graphql?.query||e.options.graphql?.endpoint?15:"graphql"===e.located.pathItem?.["x-protocol"]?12:0;var r}plan(e){const t=C(e.located,e.spec,e.options),r=[{key:"graphqlEndpoint",value:t.endpoint,type:"default",enabled:!0},...Object.entries(e.options.variables??{}).filter(([e])=>"graphqlEndpoint"!==e).map(([e,t])=>({key:e,value:null==t?"":String(t),type:g(e)?"secret":"default",enabled:!0}))];return{config:t,environment:{id:`protokit-graphql-env-${Date.now().toString(36)}-${(16777215*Math.random()|0).toString(36)}`,name:`${e.spec?.info?.title??"API"} GraphQL Environment`,values:r,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}}execute(e,t,r){return F(e.config,t,r)}};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { L as LocatedOperation, E as ExecuteContext, P as ProtocolAdapter, A as AdapterContext } from '../../protocol-Dh-wN2nY.cjs';
|
|
2
|
+
import { a as SendOptions, aj as ResolvedGraphQLConfig, E as ExecResult, Y as IntrospectionResult, X as IntrospectedSchema, l as GeneratedOperation, m as GraphQLArg, q as GraphQLTypeRef, aB as WriteGraphQLOptions, D as DiscoverAndWriteResult } from '../../types-C9ifzKqk.cjs';
|
|
3
|
+
export { n as GraphQLFieldInfo, o as GraphQLNamedType } from '../../types-C9ifzKqk.cjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the effective GraphQL call.
|
|
7
|
+
*
|
|
8
|
+
* Precedence for each field: `options.graphql.*` (explicit per-call override)
|
|
9
|
+
* > `operation['x-graphql'].*` (the document's declared operation, normally
|
|
10
|
+
* produced by {@link writeGraphQLOperations}) > a bare `POST {server}/graphql`
|
|
11
|
+
* fallback with no query, which is rejected below.
|
|
12
|
+
*/
|
|
13
|
+
declare function resolveGraphQLConfig(located: LocatedOperation, spec: any, options: SendOptions): ResolvedGraphQLConfig;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Run one GraphQL operation over HTTP.
|
|
17
|
+
*
|
|
18
|
+
* A GraphQL error is not a transport failure: the server still answers 200
|
|
19
|
+
* with a `data`/`errors` envelope, so `ExecResult.error` is only set when the
|
|
20
|
+
* call never produced a usable envelope at all (network failure, non-JSON
|
|
21
|
+
* body, or `errors` with no `data`). Partial success (`data` alongside
|
|
22
|
+
* `errors`) is left in `response.body` for the caller to inspect, exactly as
|
|
23
|
+
* a real GraphQL client would surface it.
|
|
24
|
+
*/
|
|
25
|
+
declare function runGraphQL(config: ResolvedGraphQLConfig, options: SendOptions, ctx?: ExecuteContext): Promise<ExecResult>;
|
|
26
|
+
|
|
27
|
+
/** Standard GraphQL introspection query (spec-October2021), trimmed of directive locations we don't use. */
|
|
28
|
+
declare const INTROSPECTION_QUERY: string;
|
|
29
|
+
/**
|
|
30
|
+
* Auto-fetch a GraphQL server's schema via the standard introspection query.
|
|
31
|
+
* This is the GraphQL analogue of the gRPC reflection handshake: one round
|
|
32
|
+
* trip yields every operation the endpoint exposes.
|
|
33
|
+
*/
|
|
34
|
+
declare function introspectSchema(endpoint: string, init?: {
|
|
35
|
+
headers?: Record<string, string>;
|
|
36
|
+
signal?: AbortSignal;
|
|
37
|
+
}): Promise<IntrospectionResult>;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Generate a complete, runnable operation document plus a variables schema
|
|
41
|
+
* for one root field (a query, mutation or subscription).
|
|
42
|
+
*
|
|
43
|
+
* This is the GraphQL analogue of the gRPC adapter's `buildMessageTemplate`:
|
|
44
|
+
* a schema was just fetched, and this turns it into something a caller can
|
|
45
|
+
* send immediately without hand-writing GraphQL.
|
|
46
|
+
*/
|
|
47
|
+
declare function generateOperation(operationType: "query" | "mutation" | "subscription", field: {
|
|
48
|
+
name: string;
|
|
49
|
+
args: GraphQLArg[];
|
|
50
|
+
type: GraphQLTypeRef;
|
|
51
|
+
}, schema: IntrospectedSchema): GeneratedOperation;
|
|
52
|
+
/** Enumerate every generatable operation across Query/Mutation/Subscription. */
|
|
53
|
+
declare function generateAllOperations(schema: IntrospectedSchema): GeneratedOperation[];
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* "Upload" step: merge generated GraphQL operations into `spec.paths` as
|
|
57
|
+
* synthetic POST operations carrying an `x-graphql` extension. Each becomes
|
|
58
|
+
* independently addressable via `locateOperation({ operationId })`, exactly
|
|
59
|
+
* like any hand-authored REST operation — this is what lets `send()` resolve
|
|
60
|
+
* to the GraphQL adapter afterward.
|
|
61
|
+
*/
|
|
62
|
+
declare function writeGraphQLOperations(spec: any, endpoint: string, operations: GeneratedOperation[], options?: WriteGraphQLOptions): any;
|
|
63
|
+
/**
|
|
64
|
+
* One-shot "auto-fetch query + upload": introspect the live schema, generate
|
|
65
|
+
* a runnable document for every query/mutation/subscription field, and merge
|
|
66
|
+
* the results into the document. This is the GraphQL counterpart of the gRPC
|
|
67
|
+
* adapter's `discover()` + `buildMessageTemplate()` pair, collapsed into a
|
|
68
|
+
* single call because GraphQL introspection already returns the whole schema
|
|
69
|
+
* in one round trip.
|
|
70
|
+
*/
|
|
71
|
+
declare function discoverAndWriteGraphQLSchema(spec: any, endpoint: string, options?: WriteGraphQLOptions): Promise<DiscoverAndWriteResult>;
|
|
72
|
+
|
|
73
|
+
interface GraphQLPlan {
|
|
74
|
+
config: ResolvedGraphQLConfig;
|
|
75
|
+
environment: Record<string, any>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* GraphQL adapter.
|
|
79
|
+
*
|
|
80
|
+
* An operation is claimed when it declares `x-protocol: graphql`, carries an
|
|
81
|
+
* `x-graphql` extension (normally produced by
|
|
82
|
+
* {@link writeGraphQLOperations}), or the caller passes `options.graphql`.
|
|
83
|
+
* GraphQL is transported over plain HTTP, but the request/response shape
|
|
84
|
+
* (a single query document plus a data/errors envelope) does not fit the
|
|
85
|
+
* Postman-collection pipeline the HTTP adapter is built around, so it gets
|
|
86
|
+
* its own adapter — the same reasoning that gives WebSocket its own.
|
|
87
|
+
*/
|
|
88
|
+
declare class GraphQLAdapter implements ProtocolAdapter<GraphQLPlan> {
|
|
89
|
+
readonly name = "graphql";
|
|
90
|
+
supports(ctx: AdapterContext): number;
|
|
91
|
+
plan(ctx: AdapterContext): GraphQLPlan;
|
|
92
|
+
execute(plan: GraphQLPlan, options: SendOptions, ctx?: ExecuteContext): Promise<ExecResult>;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export { DiscoverAndWriteResult, GeneratedOperation, GraphQLAdapter, GraphQLArg, type GraphQLPlan, GraphQLTypeRef, INTROSPECTION_QUERY, IntrospectedSchema, IntrospectionResult, WriteGraphQLOptions, discoverAndWriteGraphQLSchema, generateAllOperations, generateOperation, introspectSchema, resolveGraphQLConfig, runGraphQL, writeGraphQLOperations };
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { L as LocatedOperation, E as ExecuteContext, P as ProtocolAdapter, A as AdapterContext } from '../../protocol-D7sEx8IP.js';
|
|
2
|
+
import { a as SendOptions, aj as ResolvedGraphQLConfig, E as ExecResult, Y as IntrospectionResult, X as IntrospectedSchema, l as GeneratedOperation, m as GraphQLArg, q as GraphQLTypeRef, aB as WriteGraphQLOptions, D as DiscoverAndWriteResult } from '../../types-C9ifzKqk.js';
|
|
3
|
+
export { n as GraphQLFieldInfo, o as GraphQLNamedType } from '../../types-C9ifzKqk.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the effective GraphQL call.
|
|
7
|
+
*
|
|
8
|
+
* Precedence for each field: `options.graphql.*` (explicit per-call override)
|
|
9
|
+
* > `operation['x-graphql'].*` (the document's declared operation, normally
|
|
10
|
+
* produced by {@link writeGraphQLOperations}) > a bare `POST {server}/graphql`
|
|
11
|
+
* fallback with no query, which is rejected below.
|
|
12
|
+
*/
|
|
13
|
+
declare function resolveGraphQLConfig(located: LocatedOperation, spec: any, options: SendOptions): ResolvedGraphQLConfig;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Run one GraphQL operation over HTTP.
|
|
17
|
+
*
|
|
18
|
+
* A GraphQL error is not a transport failure: the server still answers 200
|
|
19
|
+
* with a `data`/`errors` envelope, so `ExecResult.error` is only set when the
|
|
20
|
+
* call never produced a usable envelope at all (network failure, non-JSON
|
|
21
|
+
* body, or `errors` with no `data`). Partial success (`data` alongside
|
|
22
|
+
* `errors`) is left in `response.body` for the caller to inspect, exactly as
|
|
23
|
+
* a real GraphQL client would surface it.
|
|
24
|
+
*/
|
|
25
|
+
declare function runGraphQL(config: ResolvedGraphQLConfig, options: SendOptions, ctx?: ExecuteContext): Promise<ExecResult>;
|
|
26
|
+
|
|
27
|
+
/** Standard GraphQL introspection query (spec-October2021), trimmed of directive locations we don't use. */
|
|
28
|
+
declare const INTROSPECTION_QUERY: string;
|
|
29
|
+
/**
|
|
30
|
+
* Auto-fetch a GraphQL server's schema via the standard introspection query.
|
|
31
|
+
* This is the GraphQL analogue of the gRPC reflection handshake: one round
|
|
32
|
+
* trip yields every operation the endpoint exposes.
|
|
33
|
+
*/
|
|
34
|
+
declare function introspectSchema(endpoint: string, init?: {
|
|
35
|
+
headers?: Record<string, string>;
|
|
36
|
+
signal?: AbortSignal;
|
|
37
|
+
}): Promise<IntrospectionResult>;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Generate a complete, runnable operation document plus a variables schema
|
|
41
|
+
* for one root field (a query, mutation or subscription).
|
|
42
|
+
*
|
|
43
|
+
* This is the GraphQL analogue of the gRPC adapter's `buildMessageTemplate`:
|
|
44
|
+
* a schema was just fetched, and this turns it into something a caller can
|
|
45
|
+
* send immediately without hand-writing GraphQL.
|
|
46
|
+
*/
|
|
47
|
+
declare function generateOperation(operationType: "query" | "mutation" | "subscription", field: {
|
|
48
|
+
name: string;
|
|
49
|
+
args: GraphQLArg[];
|
|
50
|
+
type: GraphQLTypeRef;
|
|
51
|
+
}, schema: IntrospectedSchema): GeneratedOperation;
|
|
52
|
+
/** Enumerate every generatable operation across Query/Mutation/Subscription. */
|
|
53
|
+
declare function generateAllOperations(schema: IntrospectedSchema): GeneratedOperation[];
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* "Upload" step: merge generated GraphQL operations into `spec.paths` as
|
|
57
|
+
* synthetic POST operations carrying an `x-graphql` extension. Each becomes
|
|
58
|
+
* independently addressable via `locateOperation({ operationId })`, exactly
|
|
59
|
+
* like any hand-authored REST operation — this is what lets `send()` resolve
|
|
60
|
+
* to the GraphQL adapter afterward.
|
|
61
|
+
*/
|
|
62
|
+
declare function writeGraphQLOperations(spec: any, endpoint: string, operations: GeneratedOperation[], options?: WriteGraphQLOptions): any;
|
|
63
|
+
/**
|
|
64
|
+
* One-shot "auto-fetch query + upload": introspect the live schema, generate
|
|
65
|
+
* a runnable document for every query/mutation/subscription field, and merge
|
|
66
|
+
* the results into the document. This is the GraphQL counterpart of the gRPC
|
|
67
|
+
* adapter's `discover()` + `buildMessageTemplate()` pair, collapsed into a
|
|
68
|
+
* single call because GraphQL introspection already returns the whole schema
|
|
69
|
+
* in one round trip.
|
|
70
|
+
*/
|
|
71
|
+
declare function discoverAndWriteGraphQLSchema(spec: any, endpoint: string, options?: WriteGraphQLOptions): Promise<DiscoverAndWriteResult>;
|
|
72
|
+
|
|
73
|
+
interface GraphQLPlan {
|
|
74
|
+
config: ResolvedGraphQLConfig;
|
|
75
|
+
environment: Record<string, any>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* GraphQL adapter.
|
|
79
|
+
*
|
|
80
|
+
* An operation is claimed when it declares `x-protocol: graphql`, carries an
|
|
81
|
+
* `x-graphql` extension (normally produced by
|
|
82
|
+
* {@link writeGraphQLOperations}), or the caller passes `options.graphql`.
|
|
83
|
+
* GraphQL is transported over plain HTTP, but the request/response shape
|
|
84
|
+
* (a single query document plus a data/errors envelope) does not fit the
|
|
85
|
+
* Postman-collection pipeline the HTTP adapter is built around, so it gets
|
|
86
|
+
* its own adapter — the same reasoning that gives WebSocket its own.
|
|
87
|
+
*/
|
|
88
|
+
declare class GraphQLAdapter implements ProtocolAdapter<GraphQLPlan> {
|
|
89
|
+
readonly name = "graphql";
|
|
90
|
+
supports(ctx: AdapterContext): number;
|
|
91
|
+
plan(ctx: AdapterContext): GraphQLPlan;
|
|
92
|
+
execute(plan: GraphQLPlan, options: SendOptions, ctx?: ExecuteContext): Promise<ExecResult>;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export { DiscoverAndWriteResult, GeneratedOperation, GraphQLAdapter, GraphQLArg, type GraphQLPlan, GraphQLTypeRef, INTROSPECTION_QUERY, IntrospectedSchema, IntrospectionResult, WriteGraphQLOptions, discoverAndWriteGraphQLSchema, generateAllOperations, generateOperation, introspectSchema, resolveGraphQLConfig, runGraphQL, writeGraphQLOperations };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Symbol.for("@powerduck/openapi-request.ProtoKitError"),t=class t extends Error{code;details;[e]=!0;constructor(e,r,n,o){if(super(e),this.name="ProtoKitError",this.code="string"==typeof r&&r?r:"UNKNOWN",this.details=n,o&&"cause"in o)try{Object.defineProperty(this,"cause",{value:o.cause,configurable:!0,writable:!0,enumerable:!1})}catch{}Object.setPrototypeOf(this,t.prototype),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,t)}static isProtoKitError(t){return"object"==typeof t&&null!==t&&!0===t[e]}toJSON(){return{name:this.name,code:this.code,message:this.message,...void 0===this.details?{}:{details:this.details}}}};function r(e,r,n,o){return new t(r,e,n,o)}function n(e){const t=typeof e;if(null===e)return"null";if("undefined"===t)return"undefined";if("function"===t){const t=e.name;return t?`[Function: ${t}]`:"[Function (anonymous)]"}if("symbol"===t)return String(e);if("bigint"===t)return`${String(e)}n`;try{const t=JSON.stringify(e);if("string"==typeof t)return t}catch{}try{return String(e)}catch{return"[unserializable value]"}}function o(e){if(t.isProtoKitError(e))return{message:e.message||"Unknown ProtoKitError",code:e.code,name:e.name};if(e instanceof Error){const t=e.code,r="string"==typeof t||"number"==typeof t?String(t):void 0;return{message:e.message||e.name||"Unknown error",...r?{code:r}:{},name:e.name||"Error"}}if("object"==typeof e&&null!==e&&"string"==typeof e.message){const t=e,r="string"==typeof t.code||"number"==typeof t.code?String(t.code):void 0;return{message:t.message||"Unknown error",...r?{code:r}:{},..."string"==typeof t.name?{name:t.name}:{}}}return"string"==typeof e?{message:e||"Unknown error"}:{message:n(e)}}var i=new Set(["__proto__","constructor","prototype"]);function s(e){return i.has(e)}function a(e){if(null===e||"object"!=typeof e)return e;if("function"==typeof globalThis.structuredClone)try{return globalThis.structuredClone(e)}catch{}return function(e){return u(e,new Set)}(e)}function u(e,t){if(null===e)return null;const r=typeof e;if("string"===r||"boolean"===r)return e;if("number"===r)return Number.isFinite(e)?e:null;if("bigint"===r)return e.toString();if("object"!==r)return;const n=e;if(t.has(n))return null;const o=n.toJSON;if("function"==typeof o){let e;try{e=o.call(n)}catch{return null}return e===n?null:u(e,t)}t.add(n);try{if(Array.isArray(n)){const e=new Array(n.length);for(let r=0;r<n.length;r+=1){const o=u(n[r],t);e[r]=void 0===o?null:o}return e}const e={};for(const r of Object.keys(n)){if(s(r))continue;let o;try{o=n[r]}catch{continue}const i=u(o,t);void 0!==i&&(e[r]=i)}return e}finally{t.delete(n)}}function c(e,t){const r=l(e);return r&&-1!==r.indexOf("{{")&&t?r.replace(/\{\{\s*([\w.$-]+)\s*\}\}/g,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;const n=t[r];return null==n?e:l(n)}):r}function l(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:""}catch{try{return String(e)}catch{return""}}}function p(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}var f=/(token|secret|password|passwd|apikey|api_key|credential|private|authorization)/i;function d(e){return f.test(e)}var h="\0PK_OPEN\0",m="\0PK_CLOSE\0";function y(e,t){const n="string"==typeof t.serverUrl?t.serverUrl.trim():"";if(n)return b(v(n),"options.serverUrl");const o=Array.isArray(e)?e.filter(p):[],i=o[Number.isInteger(t.serverIndex)?Math.max(0,t.serverIndex):0]??o[0];let s=i&&"string"==typeof i.url&&i.url.trim()?i.url.trim():"";if(!s)throw r("NO_SERVER_URL","The document declares no usable server URL. Pass options.serverUrl to specify one.");return s=function(e,t,n){const o=p(t)?t:{};let i=e;for(const[e,t]of Object.entries(o)){const o=n?.[e];let s;if(null!=o){if(s=o,Array.isArray(t?.enum)&&t.enum.length&&!t.enum.some(e=>String(e)===String(o)))throw r("BAD_SERVER_VARIABLE",`Server variable "${e}" must be one of: ${t.enum.join(", ")}`,{provided:o,allowed:t.enum})}else if(void 0!==t?.default)s=t.default;else{if(!Array.isArray(t?.enum)||!t.enum.length)throw r("BAD_SERVER_VARIABLE",`Server variable "${e}" has no default; pass serverVariables["${e}"].`);s=t.enum[0]}i=i.split(`{${e}}`).join(String(s??""))}for(const[e,t]of Object.entries(n??{}))Object.prototype.hasOwnProperty.call(o,e)||null!=t&&(i=i.split(`{${e}}`).join(String(t)));return i}(s,i?.variables,t.serverVariables),b(v(s),"spec.servers")}function v(e){return e.replace(/\/+$/,"")||e}function b(e,t){const n=function(e){return-1===e.indexOf("{")?e:e.split("{{").join(h).split("}}").join(m).replace(/\{[^{}]*\}/g,"").split(h).join("{{").split(m).join("}}")}(e);if(!n)throw r("BAD_SERVER_URL",`${t} resolved to an empty URL`);if(n.includes("{{"))return n;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(n))throw r("RELATIVE_SERVER_URL",`${t} resolved to the relative URL "${n}". A request needs an absolute origin; pass options.serverUrl.`,{url:n});return n}var g=new Set(["__proto__","constructor","prototype"]),A="2024-01-01T00:00:00.000Z";function E(e,t=0,r={}){const n=r.maxDepth??12;if(!e||"object"!=typeof e||Array.isArray(e))return null;if(t>n)return null;if("string"==typeof e.$ref)return null;if(void 0!==e.example)return e.example;const o=function(e){if(null==e)return;if(Array.isArray(e))return e.length?e[0]:void 0;if("object"==typeof e)for(const t of Object.values(e))if(void 0!==t){if(t&&"object"==typeof t){if("value"in t)return t.value;if("externalValue"in t)continue}return t}return}(e.examples);if(void 0!==o)return o;if(void 0!==e.default)return e.default;if(void 0!==e.const)return e.const;if(Array.isArray(e.enum)&&e.enum.length){const t=e.enum.find(e=>null!==e);return void 0!==t?t:e.enum[0]}if(Array.isArray(e.allOf)&&e.allOf.length)return function(e,t,r){let n,o;for(const i of e.allOf){const e=E(i,t+1,r);null===e||"object"!=typeof e||Array.isArray(e)?null!=e&&(o=e):n={...n??{},...e}}if(e.properties||e.required){const o=T(e,t,r);o&&"object"==typeof o&&(n={...n??{},...o})}return n||(void 0!==o?o:{})}(e,t,r);for(const n of["oneOf","anyOf"]){const o=e[n];if(Array.isArray(o)&&o.length){return E(o.find(e=>e&&"object"==typeof e&&"null"!==e.type)??o[0],t+1,r)}}const i=function(e){const t=Array.isArray(e.type)?e.type.find(e=>"string"==typeof e&&"null"!==e)??(e.type.includes("null")?"null":void 0):"string"==typeof e.type?e.type:void 0;if(t)return t;if(e.properties||e.additionalProperties||e.required)return"object";if(e.items||e.prefixItems)return"array";if(void 0!==e.minimum||void 0!==e.maximum||void 0!==e.multipleOf)return"number";return"string"}(e);switch(i){case"object":return T(e,t,r);case"array":return function(e,t,r){const n=[];if(Array.isArray(e.prefixItems))for(const o of e.prefixItems)n.push(E(o,t+1,r));const o=S(e.minItems)??1,i=S(e.maxItems);let s=Math.max(o,n.length,1);s=Math.min(s,5),void 0!==i&&(s=Math.min(s,Math.max(i,0)));const a=e.items&&"object"==typeof e.items?e.items:void 0;if(!a&&Array.isArray(e.prefixItems))return n.slice(0,0===s?0:Math.max(s,n.length));for(;n.length<s;){const o=E(a??{},t+1,r);if(!0===e.uniqueItems&&n.length>0)break;n.push(o)}return void 0!==i?n.slice(0,Math.max(i,0)):n}(e,t,r);case"integer":return function(e){const{min:t,max:r}=x(e,!0);let n=0;void 0!==t&&n<t&&(n=Math.ceil(t));void 0!==r&&n>r&&(n=Math.floor(r));const o=w(e.multipleOf);if(void 0!==o&&o>0){const e=Math.ceil(n/o)*o;(void 0===r||e<=r)&&(n=e)}return Math.trunc(n)}(e);case"number":return function(e){const{min:t,max:r}=x(e,!1);let n=0;void 0!==t&&n<t&&(n=t);void 0!==r&&n>r&&(n=r);const o=w(e.multipleOf);if(void 0!==o&&o>0){const e=Math.ceil(n/o)*o;(void 0===r||e<=r)&&(n=e)}return n}(e);case"boolean":return!1;case"null":return null;default:return function(e){const t="string"==typeof e.format?e.format:void 0,r=t?function(e){switch(e){case"date-time":return A;case"date":return A.slice(0,10);case"time":return A.slice(11,19);case"duration":return"PT1S";case"uuid":return"00000000-0000-4000-8000-000000000000";case"email":case"idn-email":return"user@example.com";case"hostname":case"idn-hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"uri":case"url":case"iri":return"https://example.com";case"uri-reference":case"iri-reference":case"json-pointer":return"/example";case"uri-template":return"https://example.com/{id}";case"relative-json-pointer":return"0/example";case"regex":return"^example$";case"byte":return"ZXhhbXBsZQ==";case"binary":return"";case"password":return"password";default:return}}(t):void 0;return void 0!==r?O(r,e):"string"==typeof e.pattern&&e.pattern.length?"":O("string",e)}(e)}}function T(e,t,r){const n={},o=Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[],i=e.properties&&"object"==typeof e.properties?e.properties:{},s=!0===r.includeReadOnly,a=!1!==r.includeWriteOnly;for(const[e,u]of Object.entries(i))g.has(e)||!s&&u&&!0===u.readOnly||!a&&u&&!0===u.writeOnly||t>2&&o.length&&!o.includes(e)||(n[e]=E(u,t+1,r));for(const e of o)g.has(e)||e in n||(n[e]=E(i[e]??{},t+1,r));!Object.keys(n).length&&e.additionalProperties&&"object"==typeof e.additionalProperties&&(n.key=E(e.additionalProperties,t+1,r));const u=S(e.minProperties);if(void 0!==u){const o=e.additionalProperties&&"object"==typeof e.additionalProperties?e.additionalProperties:{};let i=1;for(;Object.keys(n).length<Math.min(u,20);){const e=`additionalProp${i}`;i+=1,e in n||(n[e]=E(o,t+1,r))}}return n}function x(e,t){const r=t?1:Number.EPSILON>0?1e-6:1;let n=w(e.minimum),o=w(e.maximum);const i=e.exclusiveMinimum,s=e.exclusiveMaximum;if("number"==typeof i&&Number.isFinite(i)){const e=i+r;n=void 0===n?e:Math.max(n,e)}else!0===i&&void 0!==n&&(n+=r);if("number"==typeof s&&Number.isFinite(s)){const e=s-r;o=void 0===o?e:Math.min(o,e)}else!0===s&&void 0!==o&&(o-=r);return{min:n,max:o}}function O(e,t){const r=S(t.minLength),n=S(t.maxLength);let o=e;return void 0!==r&&o.length<r&&(o=o.padEnd(Math.min(r,256),"x")),void 0!==n&&o.length>n&&(o=o.slice(0,Math.max(n,0))),o}function w(e){if("number"==typeof e&&Number.isFinite(e))return e}function S(e){const t=w(e);if(void 0===t)return;const r=Math.floor(t);return r<0?0:r}function _(e,t,n){const o=n.graphql??{},i=e.operation?.["x-graphql"],s=i&&"object"==typeof i?i:{},a={...n.variables??{}};let u;if(u=o.endpoint?o.endpoint:"string"==typeof s.endpoint&&s.endpoint?s.endpoint:y(e.servers,n),u=c(u,a),/\{\{[^}]+\}\}/.test(u))throw r("BAD_GRAPHQL_ENDPOINT",`Unresolved variable in GraphQL endpoint: ${u}`);try{const e=new URL(u);if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error("not http(s)")}catch{throw r("BAD_GRAPHQL_ENDPOINT",`GraphQL endpoint must be an absolute http(s) URL, received: ${u}`)}const l=o.query??s.query;if("string"!=typeof l||!l.trim())throw r("BAD_GRAPHQL_QUERY","No GraphQL query/mutation document was found. Provide options.graphql.query or declare it on the operation as x-graphql.query (see writeGraphQLOperations).");const f=o.operationName??("string"==typeof(d=s.operationName)&&d.length?d:void 0);var d;const h=p(s.variablesSchema)?E(s.variablesSchema):void 0,m=p(s.variables)?s.variables:void 0,v=p(n.values?.body)?n.values.body:void 0,b={...p(h)?h:{},...m??{},...v??{},...o.variables??{}},g={},A=e=>{if(p(e))for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&(g[t]=c(String(r),a))};A(n.values?.header),A(s.headers),A(o.headers),N(g,"content-type")||o.useGet||(g["Content-Type"]="application/json"),N(g,"accept")||(g.Accept="application/json, text/event-stream");const T=n.auth;if(T&&"none"!==T.type&&!N(g,"authorization"))if("bearer"===T.type)g.Authorization=`Bearer ${T.token??""}`;else if("basic"===T.type){const e=`${T.username??""}:${T.password??""}`;g.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===T.type&&"header"===(T.in??"header")&&(g[T.key??"X-API-Key"]=T.value??"");return{endpoint:u,query:l,operationName:f,variables:b,headers:g,useGet:!0===o.useGet}}function N(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t)}var q=new Set(["[DONE]","DONE","[done]","done"]),j=/\r\n\r\n|\n\n|\r\r/,$=/^\d+$/;function k(e,t){const r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.floor(r):t}var I=class{buffer="";decoder=new TextDecoder("utf-8");lastEventId;bomChecked=!1;overflowed=!1;sequence=0;maxBufferChars;maxEventChars;inheritEventId;droppedEvents=0;constructor(e={}){this.maxBufferChars=k(e.maxBufferChars,4194304),this.maxEventChars=k(e.maxEventChars,1048576),this.inheritEventId=!1!==e.inheritEventId}get truncated(){return this.overflowed}get count(){return this.sequence}push(e){if(null==e)return[];if("string"==typeof e)this.buffer+=e;else{let t;if(e instanceof Uint8Array)t=e;else try{t=new Uint8Array(e)}catch{return[]}try{this.buffer+=this.decoder.decode(t,{stream:!0})}catch{return[]}}!this.bomChecked&&this.buffer.length&&(this.bomChecked=!0,65279===this.buffer.charCodeAt(0)&&(this.buffer=this.buffer.slice(1)));const t=this.drain();return this.buffer.length>this.maxBufferChars&&(this.overflowed=!0,this.droppedEvents+=1,this.buffer=this.buffer.slice(-8)),t}flush(){try{this.buffer+=this.decoder.decode()}catch{}const e=this.drain(),t=this.buffer;if(this.buffer="",t.trim()){const r=this.parseBlock(t);r&&e.push(r)}return e}reset(){this.buffer="",this.lastEventId=void 0,this.bomChecked=!1,this.overflowed=!1,this.sequence=0,this.droppedEvents=0;try{this.decoder.decode()}catch{}}drain(){const e=[];for(;;){const t=j.exec(this.buffer);if(!t)break;const r=this.buffer.slice(0,t.index);this.buffer=this.buffer.slice(t.index+t[0].length);const n=this.parseBlock(r);n&&e.push(n)}return e}parseBlock(e){const t=e.split(/\r\n|\n|\r/),r=[],n={data:"",receivedAt:Date.now(),direction:"in"};let o=!1,i=0,s=!1;for(const e of t){if(""===e)continue;if(58===e.charCodeAt(0))continue;const t=e.indexOf(":"),a=-1===t?e:e.slice(0,t);let u=-1===t?"":e.slice(t+1);switch(32===u.charCodeAt(0)&&(u=u.slice(1)),a){case"data":{if(o=!0,s)break;const e=this.maxEventChars-i;u.length>e?(r.push(u.slice(0,Math.max(0,e))),s=!0,this.overflowed=!0,this.droppedEvents+=1):(r.push(u),i+=u.length+1);break}case"event":n.event=u,o=!0;break;case"id":u.includes("\0")||(n.id=u,this.lastEventId=u),o=!0;break;case"retry":if($.test(u)&&u.length<=15){const e=Number(u);Number.isSafeInteger(e)&&(n.retry=e)}o=!0}}if(!o)return null;if(n.data=r.join("\n"),void 0===n.id&&this.inheritEventId&&void 0!==this.lastEventId&&(n.id=this.lastEventId),!s){const e=n.data.trim();if(e&&!q.has(e)&&function(e){const t=e.charCodeAt(0);return 123===t||91===t||34===t}(e))try{n.parsed=JSON.parse(n.data)}catch{}}return this.sequence+=1,n}};function P(e){const t={};return e.forEach((e,r)=>{t[r]=t[r]?`${t[r]}, ${e}`:e}),t}async function R(e,t,r){const n=Date.now(),i=r?.signal??t.signal,s=e.useGet?function(e){const t=new URL(e.endpoint);return t.searchParams.set("query",e.query),e.operationName&&t.searchParams.set("operationName",e.operationName),Object.keys(e.variables).length&&t.searchParams.set("variables",JSON.stringify(e.variables)),t.toString()}(e):e.endpoint,a=e.useGet?void 0:JSON.stringify({query:e.query,variables:e.variables,...e.operationName?{operationName:e.operationName}:{}}),u="number"==typeof t.timeout&&t.timeout>0?t.timeout:3e4,c=new AbortController,l=()=>c.abort();i?.addEventListener("abort",l,{once:!0});const p=setTimeout(()=>c.abort(),u);let f;p.unref?.();try{f=await fetch(s,{method:e.useGet?"GET":"POST",headers:e.headers,body:a,signal:c.signal})}catch(t){clearTimeout(p),i?.removeEventListener("abort",l);const r=Date.now(),u=!0===i?.aborted;return{protocol:"http",request:{method:e.useGet?"GET":"POST",url:s,headers:e.headers,body:a},response:{status:0,statusText:u?"Aborted":"Request failed",headers:{},timings:{startedAt:n,endedAt:r,durationMs:r-n},sizeBytes:0},error:u?{message:"GraphQL request aborted",code:"ABORTED"}:o(t)}}const d=Date.now(),h=f.headers.get("content-type")??void 0,m=!!h&&/text\/event-stream/i.test(h);let y,v,b,g,A=0;try{if(m&&f.body){const e=new I({maxBufferChars:t.maxBufferChars,maxEventChars:t.maxEventChars,inheritEventId:t.inheritEventId});b=[];const r="number"==typeof t.maxEvents&&t.maxEvents>0?t.maxEvents:100,n=f.body.getReader();for(;;){const{done:t,value:o}=await n.read();if(t)break;A+=o?.byteLength??0;for(const t of e.push(o))if(b.push(t),b.length>=r)break;if(b.length>=r){try{await n.cancel()}catch{}break}}for(const t of e.flush())b.length<r&&b.push(t)}else{const e=await f.text();if(A=e.length,v=e,h&&/json/i.test(h)&&e.trim())try{y=JSON.parse(e)}catch{}}}catch(e){g=o(e)}finally{clearTimeout(p),i?.removeEventListener("abort",l)}const E=Date.now();if(!g&&!m&&L(y)){const e=void 0!==y.data&&null!==y.data,t=Array.isArray(y.errors)?y.errors:void 0;!e&&t?.length&&(g={message:t.map(e=>e?.message).filter(Boolean).join("; ")||"GraphQL request returned errors",code:"GRAPHQL_ERRORS"})}return g||f.ok||L(y)||(g={message:`GraphQL endpoint responded HTTP ${f.status}`,code:String(f.status)}),{protocol:"http",request:{method:e.useGet?"GET":"POST",url:s,headers:e.headers,body:e.useGet?void 0:{query:e.query,variables:e.variables,operationName:e.operationName}},response:{status:f.status,statusText:f.statusText,headers:P(f.headers),contentType:h,...m?{events:b}:{body:y,text:v},timings:{startedAt:n,endedAt:E,durationMs:E-n,firstByteMs:d-n},sizeBytes:A},...g?{error:g}:{}}}function L(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var C="\nquery IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types { ...FullType }\n }\n}\nfragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args { ...InputValue }\n type { ...TypeRef }\n isDeprecated\n deprecationReason\n }\n inputFields { ...InputValue }\n enumValues(includeDeprecated: true) { name description isDeprecated deprecationReason }\n}\nfragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n}\nfragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType { kind name }\n }\n }\n }\n }\n }\n}\n".trim();async function D(e,t={}){let n,o;try{n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...t.headers??{}},body:JSON.stringify({operationName:"IntrospectionQuery",query:C}),signal:t.signal})}catch(e){throw r("GRAPHQL_INTROSPECTION_FAILED",`Could not reach GraphQL endpoint for introspection: ${e?.message??e}`,void 0,{cause:e})}try{o=await n.json()}catch(e){throw r("GRAPHQL_INTROSPECTION_FAILED",`Introspection response was not valid JSON (HTTP ${n.status})`,void 0,{cause:e})}if(!n.ok||!o?.data?.__schema){throw r("GRAPHQL_INTROSPECTION_FAILED",`Introspection failed: ${Array.isArray(o?.errors)&&o.errors.length?o.errors.map(e=>e?.message).filter(Boolean).join("; "):`HTTP ${n.status}`}. The server may have introspection disabled.`)}const i=o.data.__schema,s=new Map;for(const e of i.types??[])e?.name&&"string"==typeof e.name&&(e.name.startsWith("__")||s.set(e.name,e));return{schema:{queryType:i.queryType?.name??void 0,mutationType:i.mutationType?.name??void 0,subscriptionType:i.subscriptionType?.name??void 0,types:s},raw:i}}function B(e){let t=e,r=!0,n=0,o=!1;for(;t;)if("NON_NULL"!==t.kind){if("LIST"!==t.kind)return 0===n&&(r=!o),{named:t.name??void 0,nullable:r,listDepth:n};n+=1,r=!o,o=!1,t=t.ofType??null}else o=!0,t=t.ofType??null;return{nullable:!0,listDepth:n}}var G={ID:{type:"string"},String:{type:"string"},Int:{type:"integer"},Float:{type:"number"},Boolean:{type:"boolean"}};function M(e,t,r){const{named:n,nullable:o,listDepth:i}=B(e.type);let s;const a=n?t.types.get(n):void 0;if(n&&G[n])s={...G[n]};else if("ENUM"===a?.kind)s={type:"string",enum:(a.enumValues??[]).map(e=>e.name)};else if("INPUT_OBJECT"===a?.kind){const e={},n=[];for(const o of a.inputFields??[]){e[o.name]=M(o,t,r);B(o.type).nullable||null!=o.defaultValue||n.push(o.name)}s={type:"object",properties:e,...n.length?{required:n}:{}}}else n&&!G[n]&&r.push(`Argument "${e.name}" has custom scalar type "${n}"; sampled as a string.`),s={type:"string"};for(let e=0;e<i;e+=1)s={type:"array",items:s};return o&&(s.nullable=!0),s}function U(e,t,r,n){if(!e)return"__typename";const o=t.types.get(e);if(!o||!Array.isArray(o.fields)||!o.fields.length)return"__typename";if(n.has(e)||r<=0)return"__typename";n.add(e);const i=[];for(const e of o.fields){if(e.isDeprecated)continue;if((e.args??[]).some(e=>!B(e.type).nullable))continue;const{named:o,listDepth:s}=B(e.type),a=o?t.types.get(o):void 0;if(!a||"SCALAR"===a.kind||"ENUM"===a.kind||!!G[o??""])i.push(e.name);else if("OBJECT"===a?.kind||"INTERFACE"===a?.kind||"UNION"===a?.kind){if(r<=1)continue;const s=U(o,t,r-1,new Set(n));i.push(`${e.name} { ${s} }`)}if(i.length>=12)break}return i.length?i.join(" "):"__typename"}function Q(e,t,r){const n=[],o={},i=[],s=[],a=[];for(const e of t.args??[]){const{named:t,nullable:u,listDepth:c}=B(e.type);let l=t??"String";for(let e=0;e<c;e+=1)l=`[${l}]`;u||(l+="!"),s.push(`$${e.name}: ${l}`),a.push(`${e.name}: $${e.name}`),o[e.name]=M(e,r,n),u||null!=e.defaultValue||i.push(e.name)}const{named:u,listDepth:c}=B(t.type),l=u?r.types.get(u):void 0,p=l&&("OBJECT"===l.kind||"INTERFACE"===l.kind||"UNION"===l.kind)?` { ${U(u,r,2,new Set)} }`:"",f=`${F(e)}_${F(t.name)}`,d=s.length?`(${s.join(", ")})`:"",h=a.length?`(${a.join(", ")})`:"",m=`${e} ${f}${d} {\n ${t.name}${h}${p}\n}`;return{operationType:e,fieldName:t.name,operationName:f,query:m,variablesSchema:{type:"object",properties:o,required:i},notes:n}}function V(e){const t=[],r=[[e.queryType,"query"],[e.mutationType,"mutation"],[e.subscriptionType,"subscription"]];for(const[n,o]of r){if(!n)continue;const r=e.types.get(n);for(const n of r?.fields??[])t.push(Q(o,n,e))}return t}function F(e){return e?e[0].toUpperCase()+e.slice(1):e}function J(e){return`/graphql/${e.operationType}/${e.fieldName}`}function H(e,t,n,o={}){if(!e||"object"!=typeof e||Array.isArray(e))throw r("BAD_SPEC","spec must be an object");const i=!1!==o.overwrite,s=a(e);p(s.paths)||(s.paths={});for(const e of n){const r=J(e);!i&&p(s.paths[r])||(s.paths[r]={post:{operationId:`graphql_${e.operationType}_${e.fieldName}`,summary:`GraphQL ${e.operationType}: ${e.fieldName}`,"x-protocol":"graphql","x-graphql":{endpoint:t,operationType:e.operationType,operationName:e.operationName,query:e.query,variablesSchema:e.variablesSchema},requestBody:{required:e.variablesSchema.required.length>0,content:{"application/json":{schema:{type:"object",properties:e.variablesSchema.properties,required:e.variablesSchema.required}}}},responses:{200:{description:"GraphQL response envelope (data/errors)."}},...e.notes.length?{"x-graphql-notes":e.notes}:{}}})}return s}async function z(e,t,r={}){const{schema:n}=await D(t,{headers:r.headers,signal:r.signal}),o=V(n),i=o.flatMap(e=>e.notes.map(t=>`${e.operationType} ${e.fieldName}: ${t}`));o.length||i.push("Introspection succeeded but the schema declares no query, mutation or subscription fields.");return{spec:H(e,t,o,r),operations:o,warnings:i}}var K=class{name="graphql";supports(e){const t=e.located.operation??{};return"graphql"===t["x-protocol"]?20:(r=t["x-graphql"])&&"object"==typeof r&&!Array.isArray(r)||e.options.graphql?.query||e.options.graphql?.endpoint?15:"graphql"===e.located.pathItem?.["x-protocol"]?12:0;var r}plan(e){const t=_(e.located,e.spec,e.options),r=[{key:"graphqlEndpoint",value:t.endpoint,type:"default",enabled:!0},...Object.entries(e.options.variables??{}).filter(([e])=>"graphqlEndpoint"!==e).map(([e,t])=>({key:e,value:null==t?"":String(t),type:d(e)?"secret":"default",enabled:!0}))];return{config:t,environment:{id:`protokit-graphql-env-${Date.now().toString(36)}-${(16777215*Math.random()|0).toString(36)}`,name:`${e.spec?.info?.title??"API"} GraphQL Environment`,values:r,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}}execute(e,t,r){return R(e.config,t,r)}};export{K as GraphQLAdapter,C as INTROSPECTION_QUERY,z as discoverAndWriteGraphQLSchema,V as generateAllOperations,Q as generateOperation,D as introspectSchema,_ as resolveGraphQLConfig,R as runGraphQL,H as writeGraphQLOperations};
|