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

@apollo/explorer

Package Overview
Dependencies
Maintainers
1
Versions
31
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@apollo/explorer - npm Package Compare versions

Comparing version 1.0.0 to 1.1.0

EmbeddedExplorer-ecaace2f.js

796

EmbeddedExplorer.development.js
'use strict';
var graphqlWs = require('graphql-ws');
var subscriptionsTransportWs = require('subscriptions-transport-ws');
// URL for any embedded Explorer iframe
var EMBEDDABLE_EXPLORER_URL = 'https://explorer.embed.apollographql.com';
const EMBEDDABLE_EXPLORER_URL = 'https://explorer.embed.apollographql.com';
var EXPLORER_LISTENING_FOR_SCHEMA = 'ExplorerListeningForSchema';
var SCHEMA_RESPONSE = 'SchemaResponse'; // Message types for queries and mutations
const EXPLORER_LISTENING_FOR_SCHEMA = 'ExplorerListeningForSchema';
const SCHEMA_RESPONSE = 'SchemaResponse'; // Message types for queries and mutations
var EXPLORER_QUERY_MUTATION_REQUEST = 'ExplorerRequest';
var EXPLORER_QUERY_MUTATION_RESPONSE = 'ExplorerResponse'; // Message types for subscriptions
var IFRAME_DOM_ID = function (uniqueId) {
return "apollo-embed-" + uniqueId;
}; // Message types for authentication
const EXPLORER_QUERY_MUTATION_REQUEST = 'ExplorerRequest';
const EXPLORER_QUERY_MUTATION_RESPONSE = 'ExplorerResponse'; // Message types for subscriptions
var EXPLORER_LISTENING_FOR_HANDSHAKE = 'ExplorerListeningForHandshake';
var HANDSHAKE_RESPONSE = 'HandshakeResponse';
var SET_PARTIAL_AUTHENTICATION_TOKEN_FOR_PARENT = 'SetPartialAuthenticationTokenForParent';
var TRIGGER_LOGOUT_IN_PARENT = 'TriggerLogoutInParent';
var EXPLORER_LISTENING_FOR_PARTIAL_TOKEN = 'ExplorerListeningForPartialToken';
var PARTIAL_AUTHENTICATION_TOKEN_RESPONSE = 'PartialAuthenticationTokenResponse';
var PARENT_LOGOUT_SUCCESS = 'ParentLogoutSuccess';
const EXPLORER_SUBSCRIPTION_REQUEST = 'ExplorerSubscriptionRequest';
const EXPLORER_SUBSCRIPTION_RESPONSE = 'ExplorerSubscriptionResponse';
const EXPLORER_SUBSCRIPTION_TERMINATION = 'ExplorerSubscriptionTermination';
const EXPLORER_SET_SOCKET_ERROR = 'ExplorerSetSocketError';
const EXPLORER_SET_SOCKET_STATUS = 'ExplorerSetSocketStatus';
const IFRAME_DOM_ID = uniqueId => `apollo-embed-${uniqueId}`; // Message types for authentication
const EXPLORER_LISTENING_FOR_HANDSHAKE = 'ExplorerListeningForHandshake';
const HANDSHAKE_RESPONSE = 'HandshakeResponse';
const SET_PARTIAL_AUTHENTICATION_TOKEN_FOR_PARENT = 'SetPartialAuthenticationTokenForParent';
const TRIGGER_LOGOUT_IN_PARENT = 'TriggerLogoutInParent';
const EXPLORER_LISTENING_FOR_PARTIAL_TOKEN = 'ExplorerListeningForPartialToken';
const PARTIAL_AUTHENTICATION_TOKEN_RESPONSE = 'PartialAuthenticationTokenResponse';
const PARENT_LOGOUT_SUCCESS = 'ParentLogoutSuccess';
const defaultHandleRequest = ({
includeCookies
}) => {
const handleRequestWithCookiePref = (endpointUrl, options) => fetch(endpointUrl, Object.assign(Object.assign({}, options), includeCookies ? {
credentials: 'include'
} : {}));
return handleRequestWithCookiePref;
};
/*! *****************************************************************************

@@ -37,15 +54,2 @@ Copyright (c) Microsoft Corporation.

***************************************************************************** */
exports.__assign = function () {
exports.__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return exports.__assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {

@@ -82,131 +86,9 @@ function adopt(value) {

}
function __generator(thisArg, body) {
var _ = {
label: 0,
sent: function () {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
return this;
}), g;
function verb(n) {
return function (v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
var defaultHandleRequest = function (_a) {
var includeCookies = _a.includeCookies;
var handleRequestWithCookiePref = function (endpointUrl, options) {
return fetch(endpointUrl, exports.__assign(exports.__assign({}, options), includeCookies ? {
credentials: 'include'
} : {}));
};
return handleRequestWithCookiePref;
};
// to each request's headers if not present
function getHeadersWithContentType(headers) {
var headersWithContentType = headers !== null && headers !== void 0 ? headers : {};
const headersWithContentType = headers !== null && headers !== void 0 ? headers : {};
if (Object.keys(headersWithContentType).every(function (key) {
return key.toLowerCase() !== 'content-type';
})) {
if (Object.keys(headersWithContentType).every(key => key.toLowerCase() !== 'content-type')) {
headersWithContentType['content-type'] = 'application/json';

@@ -218,9 +100,10 @@ }

function sendPostMessageToEmbed(_a) {
var _b;
function sendPostMessageToEmbed({
message,
embeddedIFrameElement,
embedUrl
}) {
var _a;
var message = _a.message,
embeddedIFrameElement = _a.embeddedIFrameElement,
embedUrl = _a.embedUrl;
(_b = embeddedIFrameElement === null || embeddedIFrameElement === void 0 ? void 0 : embeddedIFrameElement.contentWindow) === null || _b === void 0 ? void 0 : _b.postMessage(message, embedUrl);
(_a = embeddedIFrameElement === null || embeddedIFrameElement === void 0 ? void 0 : embeddedIFrameElement.contentWindow) === null || _a === void 0 ? void 0 : _a.postMessage(message, embedUrl);
} // | MessageEvent<{

@@ -239,2 +122,16 @@ // name: typeof EXPLORER_LISTENING_FOR_HANDSHAKE;

// | MessageEvent<{
// name: typeof EXPLORER_SUBSCRIPTION_REQUEST;
// operationId: string;
// operation: string;
// variables?: Record<string, string>;
// operationName?: string;
// headers?: Record<string, string>;
// subscriptionUrl: string;
// protocol: GraphQLSubscriptionLibrary;
// }>
// | MessageEvent<{
// name: typeof EXPLORER_SUBSCRIPTION_TERMINATION;
// operationId: string;
// }>
// | MessageEvent<{
// name: typeof EXPLORER_LISTENING_FOR_SCHEMA;

@@ -262,14 +159,13 @@ // }>

function executeOperation(_a) {
var _this = this;
var endpointUrl = _a.endpointUrl,
handleRequest = _a.handleRequest,
operation = _a.operation,
operationName = _a.operationName,
variables = _a.variables,
headers = _a.headers,
embeddedIFrameElement = _a.embeddedIFrameElement,
operationId = _a.operationId,
embedUrl = _a.embedUrl;
function executeOperation({
endpointUrl,
handleRequest,
operation,
operationName,
variables,
headers,
embeddedIFrameElement,
operationId,
embedUrl
}) {
return handleRequest(endpointUrl, {

@@ -280,42 +176,11 @@ method: 'POST',

query: operation,
variables: variables,
operationName: operationName
variables,
operationName
})
}).then(function (response) {
return __awaiter(_this, void 0, void 0, function () {
var json, responseHeaders;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
return [4
/*yield*/
, response.json()];
case 1:
json = _a.sent();
responseHeaders = {};
response.headers.forEach(function (value, key) {
responseHeaders[key] = value;
});
sendPostMessageToEmbed({
message: {
// Include the same operation ID in the response message's name
// so the Explorer knows which operation it's associated with
name: EXPLORER_QUERY_MUTATION_RESPONSE,
operationId: operationId,
response: exports.__assign(exports.__assign({}, json), {
status: response.status,
headers: responseHeaders
})
},
embeddedIFrameElement: embeddedIFrameElement,
embedUrl: embedUrl
});
return [2
/*return*/
];
}
});
}).then(response => __awaiter(this, void 0, void 0, function* () {
const json = yield response.json();
const responseHeaders = {};
response.headers.forEach((value, key) => {
responseHeaders[key] = value;
});
})["catch"](function (response) {
sendPostMessageToEmbed({

@@ -326,5 +191,20 @@ message: {

name: EXPLORER_QUERY_MUTATION_RESPONSE,
operationId: operationId,
operationId,
response: Object.assign(Object.assign({}, json), {
status: response.status,
headers: responseHeaders
})
},
embeddedIFrameElement,
embedUrl
});
})).catch(response => {
sendPostMessageToEmbed({
message: {
// Include the same operation ID in the response message's name
// so the Explorer knows which operation it's associated with
name: EXPLORER_QUERY_MUTATION_RESPONSE,
operationId,
response: {
error: exports.__assign({
error: Object.assign({
message: response.message

@@ -336,16 +216,19 @@ }, response.stack ? {

},
embeddedIFrameElement: embeddedIFrameElement,
embedUrl: embedUrl
embeddedIFrameElement,
embedUrl
});
});
}
var handleAuthenticationPostMessage = function (_a) {
var event = _a.event,
embeddedIFrameElement = _a.embeddedIFrameElement,
embedUrl = _a.embedUrl;
var data = event.data; // When the embed authenticates, save the partial token in local storage
const handleAuthenticationPostMessage = ({
event,
embeddedIFrameElement,
embedUrl
}) => {
const {
data
} = event; // When the embed authenticates, save the partial token in local storage
if (data.name === SET_PARTIAL_AUTHENTICATION_TOKEN_FOR_PARENT) {
var partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
var partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};
const partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
const partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};
partialEmbedApiKeys[data.localStorageKey] = data.partialToken;

@@ -357,4 +240,4 @@ window.localStorage.setItem('apolloStudioEmbeddedExplorerEncodedApiKey', JSON.stringify(partialEmbedApiKeys));

if (data.name === TRIGGER_LOGOUT_IN_PARENT) {
var partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
var partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};
const partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
const partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};
delete partialEmbedApiKeys[data.localStorageKey];

@@ -366,4 +249,4 @@ window.localStorage.setItem('apolloStudioEmbeddedExplorerEncodedApiKey', JSON.stringify(partialEmbedApiKeys));

},
embeddedIFrameElement: embeddedIFrameElement,
embedUrl: embedUrl
embeddedIFrameElement,
embedUrl
});

@@ -373,4 +256,4 @@ }

if (data.name === EXPLORER_LISTENING_FOR_PARTIAL_TOKEN && data.localStorageKey) {
var partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
var partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};
const partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
const partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};

@@ -383,4 +266,4 @@ if (partialEmbedApiKeys && partialEmbedApiKeys[data.localStorageKey]) {

},
embeddedIFrameElement: embeddedIFrameElement,
embedUrl: embedUrl
embeddedIFrameElement,
embedUrl
});

@@ -391,16 +274,303 @@ }

function setupEmbedRelay(_a) {
var endpointUrl = _a.endpointUrl,
handleRequest = _a.handleRequest,
embeddedExplorerIFrameElement = _a.embeddedExplorerIFrameElement,
updateSchemaInEmbed = _a.updateSchemaInEmbed,
schema = _a.schema,
graphRef = _a.graphRef,
autoInviteOptions = _a.autoInviteOptions;
var embedUrl = EMBEDDABLE_EXPLORER_URL; // Callback definition
function assertUnreachable(x) {
throw new Error(`Didn't expect to get here ${x}`);
}
var onPostMessageReceived = function (event) {
class SubscriptionClient {
constructor(url, headers, protocol) {
this.unsubscribeFunctions = [];
this.protocol = protocol;
this.url = url;
this.headers = headers;
}
get graphWsClient() {
var _a, _b;
const client = (_a = this._graphWsClient) !== null && _a !== void 0 ? _a : graphqlWs.createClient({
url: this.url,
lazy: true,
connectionParams: (_b = this.headers) !== null && _b !== void 0 ? _b : {},
keepAlive: 10000
});
this._graphWsClient = client;
return client;
}
get transportSubscriptionClient() {
var _a, _b;
const client = (_a = this._transportSubscriptionClient) !== null && _a !== void 0 ? _a : new subscriptionsTransportWs.SubscriptionClient(this.url, {
reconnect: true,
lazy: true,
connectionParams: (_b = this.headers) !== null && _b !== void 0 ? _b : {}
});
this._transportSubscriptionClient = client;
return client;
}
onConnected(callback) {
if (this.protocol === 'graphql-ws') {
return this.graphWsClient.on('connected', callback);
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onConnected(callback);
}
assertUnreachable(this.protocol);
}
onConnecting(callback) {
if (this.protocol === 'graphql-ws') {
return this.graphWsClient.on('connecting', callback);
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onConnecting(callback);
}
assertUnreachable(this.protocol);
}
onError(callback) {
if (this.protocol === 'graphql-ws') {
return this.graphWsClient.on('error', error => callback(error));
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onError(e => callback(e));
}
assertUnreachable(this.protocol);
}
onReconnecting(callback) {
if (this.protocol === 'graphql-ws') {
return;
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onReconnecting(callback);
}
assertUnreachable(this.protocol);
}
onReconnected(callback) {
if (this.protocol === 'graphql-ws') {
return;
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onReconnected(callback);
}
assertUnreachable(this.protocol);
}
onDisconnected(callback) {
if (this.protocol === 'graphql-ws') {
return this.graphWsClient.on('closed', callback);
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onDisconnected(callback);
}
assertUnreachable(this.protocol);
}
request(params) {
return {
subscribe: subscribeParams => {
if (this.protocol === 'graphql-ws') {
this.unsubscribeFunctions.push(this.graphWsClient.subscribe(params, Object.assign(Object.assign({}, subscribeParams), {
next: data => {
var _a;
return (_a = subscribeParams.next) === null || _a === void 0 ? void 0 : _a.call(subscribeParams, data);
},
error: error => {
var _a;
return (_a = subscribeParams.error) === null || _a === void 0 ? void 0 : _a.call(subscribeParams, error);
},
complete: () => {}
})));
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.request(params).subscribe(subscribeParams);
} else {
return undefined;
}
}
};
}
unsubscribeAll() {
if (this.protocol === 'graphql-ws') {
this.unsubscribeFunctions.forEach(off => {
off();
});
this.unsubscribeFunctions = [];
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.unsubscribeAll();
}
}
}
function setParentSocketError({
error,
embeddedIFrameElement,
embedUrl
}) {
sendPostMessageToEmbed({
message: {
name: EXPLORER_SET_SOCKET_ERROR,
error
},
embeddedIFrameElement,
embedUrl
});
}
function setParentSocketStatus({
status,
embeddedIFrameElement,
embedUrl
}) {
sendPostMessageToEmbed({
message: {
name: EXPLORER_SET_SOCKET_STATUS,
status
},
embeddedIFrameElement,
embedUrl
});
}
function executeSubscription({
operation,
operationName,
variables,
headers,
embeddedIFrameElement,
operationId,
embedUrl,
subscriptionUrl,
protocol
}) {
const client = new SubscriptionClient(subscriptionUrl, headers !== null && headers !== void 0 ? headers : {}, protocol);
const checkForSubscriptionTermination = event => {
if (event.data.name === EXPLORER_SUBSCRIPTION_TERMINATION) {
client.unsubscribeAll();
window.removeEventListener('message', checkForSubscriptionTermination);
}
};
window.addEventListener('message', checkForSubscriptionTermination);
client.onError(e => setParentSocketError({
error: JSON.parse(JSON.stringify(e)),
embeddedIFrameElement,
embedUrl
}));
client.onConnected(() => {
setParentSocketError({
error: undefined,
embeddedIFrameElement,
embedUrl
});
setParentSocketStatus({
status: 'connected',
embeddedIFrameElement,
embedUrl
});
});
client.onReconnected(() => {
setParentSocketError({
error: undefined,
embeddedIFrameElement,
embedUrl
});
setParentSocketStatus({
status: 'connected',
embeddedIFrameElement,
embedUrl
});
});
client.onConnecting(() => setParentSocketStatus({
status: 'connecting',
embeddedIFrameElement,
embedUrl
}));
client.onReconnecting(() => setParentSocketStatus({
status: 'connecting',
embeddedIFrameElement,
embedUrl
}));
client.onDisconnected(() => setParentSocketStatus({
status: 'disconnected',
embeddedIFrameElement,
embedUrl
}));
client.request({
query: operation,
variables: variables !== null && variables !== void 0 ? variables : {},
operationName
}).subscribe({
next(data) {
sendPostMessageToEmbed({
message: {
// Include the same operation ID in the response message's name
// so the Explorer knows which operation it's associated with
name: EXPLORER_SUBSCRIPTION_RESPONSE,
operationId,
response: {
data
}
},
embeddedIFrameElement,
embedUrl
});
},
error: error => {
sendPostMessageToEmbed({
message: {
// Include the same operation ID in the response message's name
// so the Explorer knows which operation it's associated with
name: EXPLORER_SUBSCRIPTION_RESPONSE,
operationId,
response: {
error: JSON.parse(JSON.stringify(error))
}
},
embeddedIFrameElement,
embedUrl
});
}
});
}
function setupEmbedRelay({
endpointUrl,
handleRequest,
embeddedExplorerIFrameElement,
updateSchemaInEmbed,
schema,
graphRef,
autoInviteOptions
}) {
const embedUrl = EMBEDDABLE_EXPLORER_URL; // Callback definition
const onPostMessageReceived = event => {
handleAuthenticationPostMessage({
event: event,
embedUrl: embedUrl,
event,
embedUrl,
embeddedIFrameElement: embeddedExplorerIFrameElement

@@ -410,3 +580,3 @@ }); // Any pm can be listened for here, not just the ones we know the

var data = typeof event.data === 'object' ? event.data : undefined;
const data = typeof event.data === 'object' ? event.data : undefined;

@@ -419,3 +589,3 @@ if (data && 'name' in data) {

name: HANDSHAKE_RESPONSE,
graphRef: graphRef,
graphRef,
inviteToken: autoInviteOptions === null || autoInviteOptions === void 0 ? void 0 : autoInviteOptions.inviteToken,

@@ -426,3 +596,3 @@ accountId: autoInviteOptions === null || autoInviteOptions === void 0 ? void 0 : autoInviteOptions.accountId,

embeddedIFrameElement: embeddedExplorerIFrameElement,
embedUrl: embedUrl
embedUrl
});

@@ -434,3 +604,3 @@ } // Embedded Explorer sends us a PM when it is ready for a schema

updateSchemaInEmbed({
schema: schema
schema
});

@@ -441,12 +611,15 @@ } // Check to see if the posted message indicates that the user is

var isQueryOrMutation = data.name === EXPLORER_QUERY_MUTATION_REQUEST; // If the user is executing a query or mutation or subscription...
const isQueryOrMutation = data.name === EXPLORER_QUERY_MUTATION_REQUEST;
const isSubscription = data.name === EXPLORER_SUBSCRIPTION_REQUEST; // If the user is executing a query or mutation or subscription...
if (isQueryOrMutation && data.operation && data.operationId) {
if ((isQueryOrMutation || isSubscription) && data.operation && data.operationId) {
// Extract the operation details from the event.data object
var operation = data.operation,
operationId = data.operationId,
operationName = data.operationName,
variables = data.variables,
headers = data.headers,
studioGraphEndpointUrl = data.endpointUrl;
const {
operation,
operationId,
operationName,
variables,
headers,
endpointUrl: studioGraphEndpointUrl
} = data;

@@ -456,11 +629,31 @@ if (isQueryOrMutation) {

endpointUrl: endpointUrl !== null && endpointUrl !== void 0 ? endpointUrl : studioGraphEndpointUrl,
handleRequest: handleRequest,
operation: operation,
operationName: operationName,
variables: variables,
headers: headers,
handleRequest,
operation,
operationName,
variables,
headers,
embeddedIFrameElement: embeddedExplorerIFrameElement,
operationId: operationId,
embedUrl: embedUrl
operationId,
embedUrl
});
} else if (isSubscription) {
if (!!schema) {
setParentSocketError({
error: new Error('you cannot run subscriptions from this embed, since you are not embedding with a registered Studio graph'),
embeddedIFrameElement: embeddedExplorerIFrameElement,
embedUrl
});
} else {
executeSubscription({
operation,
operationName,
variables,
headers,
embeddedIFrameElement: embeddedExplorerIFrameElement,
operationId,
embedUrl,
subscriptionUrl: data.subscriptionUrl,
protocol: data.protocol
});
}
}

@@ -474,5 +667,3 @@ }

return {
dispose: function () {
return window.removeEventListener('message', onPostMessageReceived);
}
dispose: () => window.removeEventListener('message', onPostMessageReceived)
};

@@ -482,3 +673,3 @@ }

var name = "@apollo/explorer";
var version = "1.0.0";
var version = "1.1.0";
var author = "packages@apollographql.com";

@@ -568,25 +759,22 @@ var license = "MIT";

var idCounter = 0;
var EmbeddedExplorer =
/** @class */
function () {
function EmbeddedExplorer(options) {
var _this = this;
let idCounter = 0;
class EmbeddedExplorer {
constructor(options) {
var _a;
this.getEmbeddedExplorerURL = function () {
this.getEmbeddedExplorerURL = () => {
var _a, _b;
var _c = _this.options.initialState || {},
document = _c.document,
variables = _c.variables,
headers = _c.headers,
displayOptions = _c.displayOptions;
var persistExplorerState = _this.options.persistExplorerState;
var graphRef = 'graphRef' in _this.options ? _this.options.graphRef : undefined;
var queryParams = {
graphRef: graphRef,
const {
document,
variables,
headers,
displayOptions
} = this.options.initialState || {};
const {
persistExplorerState
} = this.options;
const graphRef = 'graphRef' in this.options ? this.options.graphRef : undefined;
const queryParams = {
graphRef,
defaultDocument: document ? encodeURIComponent(document) : undefined,

@@ -600,15 +788,7 @@ defaultVariables: variables ? encodeURIComponent(JSON.stringify(variables, null, 2)) : undefined,

shouldShowGlobalHeader: true,
parentSupportsSubscriptions: false,
parentSupportsSubscriptions: !!graphRef,
version: packageJSON.version
};
var queryString = Object.entries(queryParams).filter(function (_a) {
_a[0];
var value = _a[1];
return value !== undefined;
}).map(function (_a) {
var key = _a[0],
value = _a[1];
return key + "=" + value;
}).join('&');
return EMBEDDABLE_EXPLORER_URL + "?" + queryString;
const queryString = Object.entries(queryParams).filter(([_, value]) => value !== undefined).map(([key, value]) => `${key}=${value}`).join('&');
return `${EMBEDDABLE_EXPLORER_URL}?${queryString}`;
};

@@ -635,3 +815,3 @@

EmbeddedExplorer.prototype.dispose = function () {
dispose() {
var _a; // remove the dom element

@@ -643,9 +823,11 @@

this.disposable.dispose();
};
}
EmbeddedExplorer.prototype.injectEmbed = function () {
injectEmbed() {
var _a;
var element;
var target = this.options.target;
let element;
const {
target
} = this.options;

@@ -658,3 +840,3 @@ if (typeof target === 'string') {

var iframeElement = document.createElement('iframe');
const iframeElement = document.createElement('iframe');
iframeElement.src = this.embeddedExplorerURL;

@@ -665,5 +847,5 @@ iframeElement.id = IFRAME_DOM_ID(this.uniqueEmbedInstanceId);

return iframeElement;
};
}
EmbeddedExplorer.prototype.validateOptions = function () {
validateOptions() {
if (!this.options.target) {

@@ -686,10 +868,11 @@ throw new Error('"target" is required');

}
};
}
EmbeddedExplorer.prototype.updateSchemaInEmbed = function (_a) {
var schema = _a.schema;
updateSchemaInEmbed({
schema
}) {
sendPostMessageToEmbed({
message: {
name: SCHEMA_RESPONSE,
schema: schema
schema
},

@@ -699,7 +882,6 @@ embeddedIFrameElement: this.embeddedExplorerIFrameElement,

});
};
}
return EmbeddedExplorer;
}();
}
exports.EmbeddedExplorer = EmbeddedExplorer;
'use strict';
var graphqlWs = require('graphql-ws');
var subscriptionsTransportWs = require('subscriptions-transport-ws');
// URL for any embedded Explorer iframe
var EMBEDDABLE_EXPLORER_URL = 'https://explorer.embed.apollographql.com';
const EMBEDDABLE_EXPLORER_URL = 'https://explorer.embed.apollographql.com';
var EXPLORER_LISTENING_FOR_SCHEMA = 'ExplorerListeningForSchema';
var SCHEMA_RESPONSE = 'SchemaResponse'; // Message types for queries and mutations
const EXPLORER_LISTENING_FOR_SCHEMA = 'ExplorerListeningForSchema';
const SCHEMA_RESPONSE = 'SchemaResponse'; // Message types for queries and mutations
var EXPLORER_QUERY_MUTATION_REQUEST = 'ExplorerRequest';
var EXPLORER_QUERY_MUTATION_RESPONSE = 'ExplorerResponse'; // Message types for subscriptions
var IFRAME_DOM_ID = function (uniqueId) {
return "apollo-embed-" + uniqueId;
}; // Message types for authentication
const EXPLORER_QUERY_MUTATION_REQUEST = 'ExplorerRequest';
const EXPLORER_QUERY_MUTATION_RESPONSE = 'ExplorerResponse'; // Message types for subscriptions
var EXPLORER_LISTENING_FOR_HANDSHAKE = 'ExplorerListeningForHandshake';
var HANDSHAKE_RESPONSE = 'HandshakeResponse';
var SET_PARTIAL_AUTHENTICATION_TOKEN_FOR_PARENT = 'SetPartialAuthenticationTokenForParent';
var TRIGGER_LOGOUT_IN_PARENT = 'TriggerLogoutInParent';
var EXPLORER_LISTENING_FOR_PARTIAL_TOKEN = 'ExplorerListeningForPartialToken';
var PARTIAL_AUTHENTICATION_TOKEN_RESPONSE = 'PartialAuthenticationTokenResponse';
var PARENT_LOGOUT_SUCCESS = 'ParentLogoutSuccess';
const EXPLORER_SUBSCRIPTION_REQUEST = 'ExplorerSubscriptionRequest';
const EXPLORER_SUBSCRIPTION_RESPONSE = 'ExplorerSubscriptionResponse';
const EXPLORER_SUBSCRIPTION_TERMINATION = 'ExplorerSubscriptionTermination';
const EXPLORER_SET_SOCKET_ERROR = 'ExplorerSetSocketError';
const EXPLORER_SET_SOCKET_STATUS = 'ExplorerSetSocketStatus';
const IFRAME_DOM_ID = uniqueId => `apollo-embed-${uniqueId}`; // Message types for authentication
const EXPLORER_LISTENING_FOR_HANDSHAKE = 'ExplorerListeningForHandshake';
const HANDSHAKE_RESPONSE = 'HandshakeResponse';
const SET_PARTIAL_AUTHENTICATION_TOKEN_FOR_PARENT = 'SetPartialAuthenticationTokenForParent';
const TRIGGER_LOGOUT_IN_PARENT = 'TriggerLogoutInParent';
const EXPLORER_LISTENING_FOR_PARTIAL_TOKEN = 'ExplorerListeningForPartialToken';
const PARTIAL_AUTHENTICATION_TOKEN_RESPONSE = 'PartialAuthenticationTokenResponse';
const PARENT_LOGOUT_SUCCESS = 'ParentLogoutSuccess';
const defaultHandleRequest = ({
includeCookies
}) => {
const handleRequestWithCookiePref = (endpointUrl, options) => fetch(endpointUrl, Object.assign(Object.assign({}, options), includeCookies ? {
credentials: 'include'
} : {}));
return handleRequestWithCookiePref;
};
/*! *****************************************************************************

@@ -37,15 +54,2 @@ Copyright (c) Microsoft Corporation.

***************************************************************************** */
exports.__assign = function () {
exports.__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return exports.__assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {

@@ -82,131 +86,9 @@ function adopt(value) {

}
function __generator(thisArg, body) {
var _ = {
label: 0,
sent: function () {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
return this;
}), g;
function verb(n) {
return function (v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
var defaultHandleRequest = function (_a) {
var includeCookies = _a.includeCookies;
var handleRequestWithCookiePref = function (endpointUrl, options) {
return fetch(endpointUrl, exports.__assign(exports.__assign({}, options), includeCookies ? {
credentials: 'include'
} : {}));
};
return handleRequestWithCookiePref;
};
// to each request's headers if not present
function getHeadersWithContentType(headers) {
var headersWithContentType = headers !== null && headers !== void 0 ? headers : {};
const headersWithContentType = headers !== null && headers !== void 0 ? headers : {};
if (Object.keys(headersWithContentType).every(function (key) {
return key.toLowerCase() !== 'content-type';
})) {
if (Object.keys(headersWithContentType).every(key => key.toLowerCase() !== 'content-type')) {
headersWithContentType['content-type'] = 'application/json';

@@ -218,9 +100,10 @@ }

function sendPostMessageToEmbed(_a) {
var _b;
function sendPostMessageToEmbed({
message,
embeddedIFrameElement,
embedUrl
}) {
var _a;
var message = _a.message,
embeddedIFrameElement = _a.embeddedIFrameElement,
embedUrl = _a.embedUrl;
(_b = embeddedIFrameElement === null || embeddedIFrameElement === void 0 ? void 0 : embeddedIFrameElement.contentWindow) === null || _b === void 0 ? void 0 : _b.postMessage(message, embedUrl);
(_a = embeddedIFrameElement === null || embeddedIFrameElement === void 0 ? void 0 : embeddedIFrameElement.contentWindow) === null || _a === void 0 ? void 0 : _a.postMessage(message, embedUrl);
} // | MessageEvent<{

@@ -239,2 +122,16 @@ // name: typeof EXPLORER_LISTENING_FOR_HANDSHAKE;

// | MessageEvent<{
// name: typeof EXPLORER_SUBSCRIPTION_REQUEST;
// operationId: string;
// operation: string;
// variables?: Record<string, string>;
// operationName?: string;
// headers?: Record<string, string>;
// subscriptionUrl: string;
// protocol: GraphQLSubscriptionLibrary;
// }>
// | MessageEvent<{
// name: typeof EXPLORER_SUBSCRIPTION_TERMINATION;
// operationId: string;
// }>
// | MessageEvent<{
// name: typeof EXPLORER_LISTENING_FOR_SCHEMA;

@@ -262,14 +159,13 @@ // }>

function executeOperation(_a) {
var _this = this;
var endpointUrl = _a.endpointUrl,
handleRequest = _a.handleRequest,
operation = _a.operation,
operationName = _a.operationName,
variables = _a.variables,
headers = _a.headers,
embeddedIFrameElement = _a.embeddedIFrameElement,
operationId = _a.operationId,
embedUrl = _a.embedUrl;
function executeOperation({
endpointUrl,
handleRequest,
operation,
operationName,
variables,
headers,
embeddedIFrameElement,
operationId,
embedUrl
}) {
return handleRequest(endpointUrl, {

@@ -280,42 +176,11 @@ method: 'POST',

query: operation,
variables: variables,
operationName: operationName
variables,
operationName
})
}).then(function (response) {
return __awaiter(_this, void 0, void 0, function () {
var json, responseHeaders;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
return [4
/*yield*/
, response.json()];
case 1:
json = _a.sent();
responseHeaders = {};
response.headers.forEach(function (value, key) {
responseHeaders[key] = value;
});
sendPostMessageToEmbed({
message: {
// Include the same operation ID in the response message's name
// so the Explorer knows which operation it's associated with
name: EXPLORER_QUERY_MUTATION_RESPONSE,
operationId: operationId,
response: exports.__assign(exports.__assign({}, json), {
status: response.status,
headers: responseHeaders
})
},
embeddedIFrameElement: embeddedIFrameElement,
embedUrl: embedUrl
});
return [2
/*return*/
];
}
});
}).then(response => __awaiter(this, void 0, void 0, function* () {
const json = yield response.json();
const responseHeaders = {};
response.headers.forEach((value, key) => {
responseHeaders[key] = value;
});
})["catch"](function (response) {
sendPostMessageToEmbed({

@@ -326,5 +191,20 @@ message: {

name: EXPLORER_QUERY_MUTATION_RESPONSE,
operationId: operationId,
operationId,
response: Object.assign(Object.assign({}, json), {
status: response.status,
headers: responseHeaders
})
},
embeddedIFrameElement,
embedUrl
});
})).catch(response => {
sendPostMessageToEmbed({
message: {
// Include the same operation ID in the response message's name
// so the Explorer knows which operation it's associated with
name: EXPLORER_QUERY_MUTATION_RESPONSE,
operationId,
response: {
error: exports.__assign({
error: Object.assign({
message: response.message

@@ -336,16 +216,19 @@ }, response.stack ? {

},
embeddedIFrameElement: embeddedIFrameElement,
embedUrl: embedUrl
embeddedIFrameElement,
embedUrl
});
});
}
var handleAuthenticationPostMessage = function (_a) {
var event = _a.event,
embeddedIFrameElement = _a.embeddedIFrameElement,
embedUrl = _a.embedUrl;
var data = event.data; // When the embed authenticates, save the partial token in local storage
const handleAuthenticationPostMessage = ({
event,
embeddedIFrameElement,
embedUrl
}) => {
const {
data
} = event; // When the embed authenticates, save the partial token in local storage
if (data.name === SET_PARTIAL_AUTHENTICATION_TOKEN_FOR_PARENT) {
var partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
var partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};
const partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
const partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};
partialEmbedApiKeys[data.localStorageKey] = data.partialToken;

@@ -357,4 +240,4 @@ window.localStorage.setItem('apolloStudioEmbeddedExplorerEncodedApiKey', JSON.stringify(partialEmbedApiKeys));

if (data.name === TRIGGER_LOGOUT_IN_PARENT) {
var partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
var partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};
const partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
const partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};
delete partialEmbedApiKeys[data.localStorageKey];

@@ -366,4 +249,4 @@ window.localStorage.setItem('apolloStudioEmbeddedExplorerEncodedApiKey', JSON.stringify(partialEmbedApiKeys));

},
embeddedIFrameElement: embeddedIFrameElement,
embedUrl: embedUrl
embeddedIFrameElement,
embedUrl
});

@@ -373,4 +256,4 @@ }

if (data.name === EXPLORER_LISTENING_FOR_PARTIAL_TOKEN && data.localStorageKey) {
var partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
var partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};
const partialEmbedApiKeysString = window.localStorage.getItem('apolloStudioEmbeddedExplorerEncodedApiKey');
const partialEmbedApiKeys = partialEmbedApiKeysString ? JSON.parse(partialEmbedApiKeysString) : {};

@@ -383,4 +266,4 @@ if (partialEmbedApiKeys && partialEmbedApiKeys[data.localStorageKey]) {

},
embeddedIFrameElement: embeddedIFrameElement,
embedUrl: embedUrl
embeddedIFrameElement,
embedUrl
});

@@ -391,16 +274,303 @@ }

function setupEmbedRelay(_a) {
var endpointUrl = _a.endpointUrl,
handleRequest = _a.handleRequest,
embeddedExplorerIFrameElement = _a.embeddedExplorerIFrameElement,
updateSchemaInEmbed = _a.updateSchemaInEmbed,
schema = _a.schema,
graphRef = _a.graphRef,
autoInviteOptions = _a.autoInviteOptions;
var embedUrl = EMBEDDABLE_EXPLORER_URL; // Callback definition
function assertUnreachable(x) {
throw new Error(`Didn't expect to get here ${x}`);
}
var onPostMessageReceived = function (event) {
class SubscriptionClient {
constructor(url, headers, protocol) {
this.unsubscribeFunctions = [];
this.protocol = protocol;
this.url = url;
this.headers = headers;
}
get graphWsClient() {
var _a, _b;
const client = (_a = this._graphWsClient) !== null && _a !== void 0 ? _a : graphqlWs.createClient({
url: this.url,
lazy: true,
connectionParams: (_b = this.headers) !== null && _b !== void 0 ? _b : {},
keepAlive: 10000
});
this._graphWsClient = client;
return client;
}
get transportSubscriptionClient() {
var _a, _b;
const client = (_a = this._transportSubscriptionClient) !== null && _a !== void 0 ? _a : new subscriptionsTransportWs.SubscriptionClient(this.url, {
reconnect: true,
lazy: true,
connectionParams: (_b = this.headers) !== null && _b !== void 0 ? _b : {}
});
this._transportSubscriptionClient = client;
return client;
}
onConnected(callback) {
if (this.protocol === 'graphql-ws') {
return this.graphWsClient.on('connected', callback);
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onConnected(callback);
}
assertUnreachable(this.protocol);
}
onConnecting(callback) {
if (this.protocol === 'graphql-ws') {
return this.graphWsClient.on('connecting', callback);
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onConnecting(callback);
}
assertUnreachable(this.protocol);
}
onError(callback) {
if (this.protocol === 'graphql-ws') {
return this.graphWsClient.on('error', error => callback(error));
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onError(e => callback(e));
}
assertUnreachable(this.protocol);
}
onReconnecting(callback) {
if (this.protocol === 'graphql-ws') {
return;
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onReconnecting(callback);
}
assertUnreachable(this.protocol);
}
onReconnected(callback) {
if (this.protocol === 'graphql-ws') {
return;
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onReconnected(callback);
}
assertUnreachable(this.protocol);
}
onDisconnected(callback) {
if (this.protocol === 'graphql-ws') {
return this.graphWsClient.on('closed', callback);
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.onDisconnected(callback);
}
assertUnreachable(this.protocol);
}
request(params) {
return {
subscribe: subscribeParams => {
if (this.protocol === 'graphql-ws') {
this.unsubscribeFunctions.push(this.graphWsClient.subscribe(params, Object.assign(Object.assign({}, subscribeParams), {
next: data => {
var _a;
return (_a = subscribeParams.next) === null || _a === void 0 ? void 0 : _a.call(subscribeParams, data);
},
error: error => {
var _a;
return (_a = subscribeParams.error) === null || _a === void 0 ? void 0 : _a.call(subscribeParams, error);
},
complete: () => {}
})));
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.request(params).subscribe(subscribeParams);
} else {
return undefined;
}
}
};
}
unsubscribeAll() {
if (this.protocol === 'graphql-ws') {
this.unsubscribeFunctions.forEach(off => {
off();
});
this.unsubscribeFunctions = [];
}
if (this.protocol === 'subscriptions-transport-ws') {
return this.transportSubscriptionClient.unsubscribeAll();
}
}
}
function setParentSocketError({
error,
embeddedIFrameElement,
embedUrl
}) {
sendPostMessageToEmbed({
message: {
name: EXPLORER_SET_SOCKET_ERROR,
error
},
embeddedIFrameElement,
embedUrl
});
}
function setParentSocketStatus({
status,
embeddedIFrameElement,
embedUrl
}) {
sendPostMessageToEmbed({
message: {
name: EXPLORER_SET_SOCKET_STATUS,
status
},
embeddedIFrameElement,
embedUrl
});
}
function executeSubscription({
operation,
operationName,
variables,
headers,
embeddedIFrameElement,
operationId,
embedUrl,
subscriptionUrl,
protocol
}) {
const client = new SubscriptionClient(subscriptionUrl, headers !== null && headers !== void 0 ? headers : {}, protocol);
const checkForSubscriptionTermination = event => {
if (event.data.name === EXPLORER_SUBSCRIPTION_TERMINATION) {
client.unsubscribeAll();
window.removeEventListener('message', checkForSubscriptionTermination);
}
};
window.addEventListener('message', checkForSubscriptionTermination);
client.onError(e => setParentSocketError({
error: JSON.parse(JSON.stringify(e)),
embeddedIFrameElement,
embedUrl
}));
client.onConnected(() => {
setParentSocketError({
error: undefined,
embeddedIFrameElement,
embedUrl
});
setParentSocketStatus({
status: 'connected',
embeddedIFrameElement,
embedUrl
});
});
client.onReconnected(() => {
setParentSocketError({
error: undefined,
embeddedIFrameElement,
embedUrl
});
setParentSocketStatus({
status: 'connected',
embeddedIFrameElement,
embedUrl
});
});
client.onConnecting(() => setParentSocketStatus({
status: 'connecting',
embeddedIFrameElement,
embedUrl
}));
client.onReconnecting(() => setParentSocketStatus({
status: 'connecting',
embeddedIFrameElement,
embedUrl
}));
client.onDisconnected(() => setParentSocketStatus({
status: 'disconnected',
embeddedIFrameElement,
embedUrl
}));
client.request({
query: operation,
variables: variables !== null && variables !== void 0 ? variables : {},
operationName
}).subscribe({
next(data) {
sendPostMessageToEmbed({
message: {
// Include the same operation ID in the response message's name
// so the Explorer knows which operation it's associated with
name: EXPLORER_SUBSCRIPTION_RESPONSE,
operationId,
response: {
data
}
},
embeddedIFrameElement,
embedUrl
});
},
error: error => {
sendPostMessageToEmbed({
message: {
// Include the same operation ID in the response message's name
// so the Explorer knows which operation it's associated with
name: EXPLORER_SUBSCRIPTION_RESPONSE,
operationId,
response: {
error: JSON.parse(JSON.stringify(error))
}
},
embeddedIFrameElement,
embedUrl
});
}
});
}
function setupEmbedRelay({
endpointUrl,
handleRequest,
embeddedExplorerIFrameElement,
updateSchemaInEmbed,
schema,
graphRef,
autoInviteOptions
}) {
const embedUrl = EMBEDDABLE_EXPLORER_URL; // Callback definition
const onPostMessageReceived = event => {
handleAuthenticationPostMessage({
event: event,
embedUrl: embedUrl,
event,
embedUrl,
embeddedIFrameElement: embeddedExplorerIFrameElement

@@ -410,3 +580,3 @@ }); // Any pm can be listened for here, not just the ones we know the

var data = typeof event.data === 'object' ? event.data : undefined;
const data = typeof event.data === 'object' ? event.data : undefined;

@@ -419,3 +589,3 @@ if (data && 'name' in data) {

name: HANDSHAKE_RESPONSE,
graphRef: graphRef,
graphRef,
inviteToken: autoInviteOptions === null || autoInviteOptions === void 0 ? void 0 : autoInviteOptions.inviteToken,

@@ -426,3 +596,3 @@ accountId: autoInviteOptions === null || autoInviteOptions === void 0 ? void 0 : autoInviteOptions.accountId,

embeddedIFrameElement: embeddedExplorerIFrameElement,
embedUrl: embedUrl
embedUrl
});

@@ -434,3 +604,3 @@ } // Embedded Explorer sends us a PM when it is ready for a schema

updateSchemaInEmbed({
schema: schema
schema
});

@@ -441,12 +611,15 @@ } // Check to see if the posted message indicates that the user is

var isQueryOrMutation = data.name === EXPLORER_QUERY_MUTATION_REQUEST; // If the user is executing a query or mutation or subscription...
const isQueryOrMutation = data.name === EXPLORER_QUERY_MUTATION_REQUEST;
const isSubscription = data.name === EXPLORER_SUBSCRIPTION_REQUEST; // If the user is executing a query or mutation or subscription...
if (isQueryOrMutation && data.operation && data.operationId) {
if ((isQueryOrMutation || isSubscription) && data.operation && data.operationId) {
// Extract the operation details from the event.data object
var operation = data.operation,
operationId = data.operationId,
operationName = data.operationName,
variables = data.variables,
headers = data.headers,
studioGraphEndpointUrl = data.endpointUrl;
const {
operation,
operationId,
operationName,
variables,
headers,
endpointUrl: studioGraphEndpointUrl
} = data;

@@ -456,11 +629,31 @@ if (isQueryOrMutation) {

endpointUrl: endpointUrl !== null && endpointUrl !== void 0 ? endpointUrl : studioGraphEndpointUrl,
handleRequest: handleRequest,
operation: operation,
operationName: operationName,
variables: variables,
headers: headers,
handleRequest,
operation,
operationName,
variables,
headers,
embeddedIFrameElement: embeddedExplorerIFrameElement,
operationId: operationId,
embedUrl: embedUrl
operationId,
embedUrl
});
} else if (isSubscription) {
if (!!schema) {
setParentSocketError({
error: new Error('you cannot run subscriptions from this embed, since you are not embedding with a registered Studio graph'),
embeddedIFrameElement: embeddedExplorerIFrameElement,
embedUrl
});
} else {
executeSubscription({
operation,
operationName,
variables,
headers,
embeddedIFrameElement: embeddedExplorerIFrameElement,
operationId,
embedUrl,
subscriptionUrl: data.subscriptionUrl,
protocol: data.protocol
});
}
}

@@ -474,5 +667,3 @@ }

return {
dispose: function () {
return window.removeEventListener('message', onPostMessageReceived);
}
dispose: () => window.removeEventListener('message', onPostMessageReceived)
};

@@ -482,3 +673,3 @@ }

var name = "@apollo/explorer";
var version = "1.0.0";
var version = "1.1.0";
var author = "packages@apollographql.com";

@@ -568,25 +759,22 @@ var license = "MIT";

var idCounter = 0;
var EmbeddedExplorer =
/** @class */
function () {
function EmbeddedExplorer(options) {
var _this = this;
let idCounter = 0;
class EmbeddedExplorer {
constructor(options) {
var _a;
this.getEmbeddedExplorerURL = function () {
this.getEmbeddedExplorerURL = () => {
var _a, _b;
var _c = _this.options.initialState || {},
document = _c.document,
variables = _c.variables,
headers = _c.headers,
displayOptions = _c.displayOptions;
var persistExplorerState = _this.options.persistExplorerState;
var graphRef = 'graphRef' in _this.options ? _this.options.graphRef : undefined;
var queryParams = {
graphRef: graphRef,
const {
document,
variables,
headers,
displayOptions
} = this.options.initialState || {};
const {
persistExplorerState
} = this.options;
const graphRef = 'graphRef' in this.options ? this.options.graphRef : undefined;
const queryParams = {
graphRef,
defaultDocument: document ? encodeURIComponent(document) : undefined,

@@ -600,15 +788,7 @@ defaultVariables: variables ? encodeURIComponent(JSON.stringify(variables, null, 2)) : undefined,

shouldShowGlobalHeader: true,
parentSupportsSubscriptions: false,
parentSupportsSubscriptions: !!graphRef,
version: packageJSON.version
};
var queryString = Object.entries(queryParams).filter(function (_a) {
_a[0];
var value = _a[1];
return value !== undefined;
}).map(function (_a) {
var key = _a[0],
value = _a[1];
return key + "=" + value;
}).join('&');
return EMBEDDABLE_EXPLORER_URL + "?" + queryString;
const queryString = Object.entries(queryParams).filter(([_, value]) => value !== undefined).map(([key, value]) => `${key}=${value}`).join('&');
return `${EMBEDDABLE_EXPLORER_URL}?${queryString}`;
};

@@ -635,3 +815,3 @@

EmbeddedExplorer.prototype.dispose = function () {
dispose() {
var _a; // remove the dom element

@@ -643,9 +823,11 @@

this.disposable.dispose();
};
}
EmbeddedExplorer.prototype.injectEmbed = function () {
injectEmbed() {
var _a;
var element;
var target = this.options.target;
let element;
const {
target
} = this.options;

@@ -658,3 +840,3 @@ if (typeof target === 'string') {

var iframeElement = document.createElement('iframe');
const iframeElement = document.createElement('iframe');
iframeElement.src = this.embeddedExplorerURL;

@@ -665,5 +847,5 @@ iframeElement.id = IFRAME_DOM_ID(this.uniqueEmbedInstanceId);

return iframeElement;
};
}
EmbeddedExplorer.prototype.validateOptions = function () {
validateOptions() {
if (!this.options.target) {

@@ -686,10 +868,11 @@ throw new Error('"target" is required');

}
};
}
EmbeddedExplorer.prototype.updateSchemaInEmbed = function (_a) {
var schema = _a.schema;
updateSchemaInEmbed({
schema
}) {
sendPostMessageToEmbed({
message: {
name: SCHEMA_RESPONSE,
schema: schema
schema
},

@@ -699,7 +882,6 @@ embeddedIFrameElement: this.embeddedExplorerIFrameElement,

});
};
}
return EmbeddedExplorer;
}();
}
exports.EmbeddedExplorer = EmbeddedExplorer;

@@ -6,2 +6,4 @@ 'use strict';

var EmbeddedExplorer = require('./EmbeddedExplorer.development.js');
require('graphql-ws');
require('subscriptions-transport-ws');

@@ -8,0 +10,0 @@

@@ -6,2 +6,4 @@ 'use strict';

var EmbeddedExplorer = require('./EmbeddedExplorer.production.min.js');
require('graphql-ws');
require('subscriptions-transport-ws');

@@ -8,0 +10,0 @@

{
"name": "@apollo/explorer",
"version": "1.0.0",
"version": "1.1.0",
"author": "packages@apollographql.com",

@@ -5,0 +5,0 @@ "license": "MIT",

@@ -5,5 +5,7 @@ 'use strict';

var React = require('react');
var EmbeddedExplorer = require('../EmbeddedExplorer.development.js');
var React = require('react');
var useDeepCompareEffect = require('use-deep-compare-effect');
require('graphql-ws');
require('subscriptions-transport-ws');

@@ -16,22 +18,19 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

function ApolloExplorerReact(props) {
var _a = React.useState(),
wrapperElement = _a[0],
setWrapperElement = _a[1];
var currentEmbedRef = React.useRef(); // we need to default to empty objects for the objects type props
const [wrapperElement, setWrapperElement] = React.useState();
const currentEmbedRef = React.useRef(); // we need to default to empty objects for the objects type props
// that show up in the useDeepCompareEffect below, because useDeepCompareEffect
// will throw if all of its deps are primitives (undefined instead of objects)
var endpointUrl = props.endpointUrl,
handleRequest = props.handleRequest,
_b = props.initialState,
initialState = _b === void 0 ? {} : _b,
persistExplorerState = props.persistExplorerState,
graphRef = props.graphRef,
_c = props.autoInviteOptions,
autoInviteOptions = _c === void 0 ? {} : _c,
includeCookies = props.includeCookies,
className = props.className,
schema = props.schema;
useDeepCompareEffect__default["default"](function () {
const {
endpointUrl,
handleRequest,
initialState = {},
persistExplorerState,
graphRef,
autoInviteOptions = {},
includeCookies,
className,
schema
} = props;
useDeepCompareEffect__default["default"](() => {
var _a;

@@ -41,6 +40,6 @@

(_a = currentEmbedRef.current) === null || _a === void 0 ? void 0 : _a.dispose();
currentEmbedRef.current = new EmbeddedExplorer.EmbeddedExplorer(EmbeddedExplorer.__assign(EmbeddedExplorer.__assign({}, props), {
currentEmbedRef.current = new EmbeddedExplorer.EmbeddedExplorer(Object.assign(Object.assign({}, props), {
target: wrapperElement
}));
return function () {
return () => {
var _a;

@@ -54,7 +53,7 @@

[endpointUrl, handleRequest, initialState, persistExplorerState, graphRef, autoInviteOptions, includeCookies, className, wrapperElement]);
React.useEffect(function () {
React.useEffect(() => {
var _a;
if (schema) (_a = currentEmbedRef.current) === null || _a === void 0 ? void 0 : _a.updateSchemaInEmbed({
schema: schema
schema
});

@@ -64,3 +63,3 @@ }, [schema, currentEmbedRef.current]);

className: className,
ref: function (element) {
ref: element => {
setWrapperElement(element);

@@ -67,0 +66,0 @@ }

@@ -5,5 +5,7 @@ 'use strict';

var React = require('react');
var EmbeddedExplorer = require('../EmbeddedExplorer.production.min.js');
var React = require('react');
var useDeepCompareEffect = require('use-deep-compare-effect');
require('graphql-ws');
require('subscriptions-transport-ws');

@@ -16,22 +18,19 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

function ApolloExplorerReact(props) {
var _a = React.useState(),
wrapperElement = _a[0],
setWrapperElement = _a[1];
var currentEmbedRef = React.useRef(); // we need to default to empty objects for the objects type props
const [wrapperElement, setWrapperElement] = React.useState();
const currentEmbedRef = React.useRef(); // we need to default to empty objects for the objects type props
// that show up in the useDeepCompareEffect below, because useDeepCompareEffect
// will throw if all of its deps are primitives (undefined instead of objects)
var endpointUrl = props.endpointUrl,
handleRequest = props.handleRequest,
_b = props.initialState,
initialState = _b === void 0 ? {} : _b,
persistExplorerState = props.persistExplorerState,
graphRef = props.graphRef,
_c = props.autoInviteOptions,
autoInviteOptions = _c === void 0 ? {} : _c,
includeCookies = props.includeCookies,
className = props.className,
schema = props.schema;
useDeepCompareEffect__default["default"](function () {
const {
endpointUrl,
handleRequest,
initialState = {},
persistExplorerState,
graphRef,
autoInviteOptions = {},
includeCookies,
className,
schema
} = props;
useDeepCompareEffect__default["default"](() => {
var _a;

@@ -41,6 +40,6 @@

(_a = currentEmbedRef.current) === null || _a === void 0 ? void 0 : _a.dispose();
currentEmbedRef.current = new EmbeddedExplorer.EmbeddedExplorer(EmbeddedExplorer.__assign(EmbeddedExplorer.__assign({}, props), {
currentEmbedRef.current = new EmbeddedExplorer.EmbeddedExplorer(Object.assign(Object.assign({}, props), {
target: wrapperElement
}));
return function () {
return () => {
var _a;

@@ -54,7 +53,7 @@

[endpointUrl, handleRequest, initialState, persistExplorerState, graphRef, autoInviteOptions, includeCookies, className, wrapperElement]);
React.useEffect(function () {
React.useEffect(() => {
var _a;
if (schema) (_a = currentEmbedRef.current) === null || _a === void 0 ? void 0 : _a.updateSchemaInEmbed({
schema: schema
schema
});

@@ -64,3 +63,3 @@ }, [schema, currentEmbedRef.current]);

className: className,
ref: function (element) {
ref: element => {
setWrapperElement(element);

@@ -67,0 +66,0 @@ }

@@ -9,6 +9,7 @@ # Apollo Studio Embeddable Explorer

You can download the @apollo/explorer npm package with `npm install @apollo/explorer`. Then, you can import the ApolloExplorer class or ApolloExplorerReact component like so:
You can download the @apollo/explorer npm package with `npm install @apollo/explorer`. Then, you can import the ApolloExplorer class or ApolloExplorer component like so:
```
import { ApolloExplorer, ApolloExplorerReact } from '@apollo/explorer';
import { ApolloExplorer } from '@apollo/explorer';
import { ApolloExplorer } from '@apollo/explorer/react';
```

@@ -21,3 +22,3 @@

```
import { ApolloExplorerReact } from '@apollo/explorer';
import { ApolloExplorer } from '@apollo/explorer/react';

@@ -27,3 +28,3 @@ function App() {

return (
<ApolloExplorerReact
<ApolloExplorer
graphRef='acephei@current',

@@ -30,0 +31,0 @@ endpointUrl='https://acephei-gateway.herokuapp.com',

@@ -13,2 +13,4 @@ export declare const EMBEDDABLE_EXPLORER_URL = "https://explorer.embed.apollographql.com";

export declare const EXPLORER_SUBSCRIPTION_TERMINATION = "ExplorerSubscriptionTermination";
export declare const EXPLORER_SET_SOCKET_ERROR = "ExplorerSetSocketError";
export declare const EXPLORER_SET_SOCKET_STATUS = "ExplorerSetSocketStatus";
export declare const IFRAME_DOM_ID: (uniqueId: number) => string;

@@ -15,0 +17,0 @@ export declare const EXPLORER_LISTENING_FOR_HANDSHAKE = "ExplorerListeningForHandshake";

@@ -1,4 +0,4 @@

import type { GraphQLError, IntrospectionQuery } from 'graphql';
import { PARTIAL_AUTHENTICATION_TOKEN_RESPONSE, EXPLORER_QUERY_MUTATION_RESPONSE, HANDSHAKE_RESPONSE, SCHEMA_ERROR, SCHEMA_RESPONSE, PARENT_LOGOUT_SUCCESS } from './constants';
import type { JSONValue } from './types';
import type { ExecutionResult, GraphQLError, IntrospectionQuery } from 'graphql';
import { PARTIAL_AUTHENTICATION_TOKEN_RESPONSE, EXPLORER_QUERY_MUTATION_RESPONSE, HANDSHAKE_RESPONSE, SCHEMA_ERROR, SCHEMA_RESPONSE, PARENT_LOGOUT_SUCCESS, EXPLORER_SUBSCRIPTION_RESPONSE, EXPLORER_SET_SOCKET_ERROR, EXPLORER_SET_SOCKET_STATUS } from './constants';
import type { JSONObject, JSONValue } from './types';
export declare type HandleRequest = (endpointUrl: string, options: Omit<RequestInit, 'headers'> & {

@@ -12,6 +12,7 @@ headers: Record<string, string>;

}): void;
declare type Error = {
declare type ResponseError = {
message: string;
stack?: string;
};
export declare type SocketStatus = 'disconnected' | 'connecting' | 'connected';
export declare type OutgoingEmbedMessage = {

@@ -38,4 +39,4 @@ name: typeof SCHEMA_ERROR;

data?: JSONValue;
error?: Error;
errors?: [Error];
error?: ResponseError;
errors?: [ResponseError];
status?: number;

@@ -45,2 +46,16 @@ headers?: Headers;

} | {
name: typeof EXPLORER_SUBSCRIPTION_RESPONSE;
operationId: string;
response: {
data?: ExecutionResult<JSONObject>;
error?: Error;
errors?: [Error];
};
} | {
name: typeof EXPLORER_SET_SOCKET_ERROR;
error: Error | undefined;
} | {
name: typeof EXPLORER_SET_SOCKET_STATUS;
status: SocketStatus;
} | {
name: typeof PARENT_LOGOUT_SUCCESS;

@@ -47,0 +62,0 @@ };

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc