Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

netlify-onegraph-internal

Package Overview
Dependencies
Maintainers
1
Versions
100
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

netlify-onegraph-internal - npm Package Compare versions

Comparing version 0.2.0 to 0.2.1

4

dist/generatedOneGraphClient.js

@@ -152,3 +152,3 @@ "use strict";

if (etag_1) {
// Make a not of the new etag for the given payload
// Make a note of the new etag for the given payload
setInCache(cache, cacheKey, [etag_1, json]);

@@ -182,3 +182,3 @@ }

return fetchNetlifyGraph({
query: "mutation CreateGraphQLSchemaMutation($input: OneGraphCreateGraphQLSchemaInput!) {\n oneGraph {\n createGraphQLSchema(input: $input) {\n graphQLSchema {\n id\n externalGraphQLSchemas {\n nodes {\n id\n endpoint\n service\n createdAt\n updatedAt\n }\n }\n parentGraphQLSchemaId\n salesforceSchema {\n id\n createdAt\n updatedAt\n }\n services {\n slug\n }\n updatedAt\n createdAt\n appId\n }\n }\n }\n}",
query: "mutation CreateGraphQLSchemaMutation($nfToken: String!, $input: OneGraphCreateGraphQLSchemaInput!) {\n oneGraph(auths: {netlifyAuth: {oauthToken: $nfToken}}) {\n createGraphQLSchema(input: $input) {\n graphQLSchema {\n id\n externalGraphQLSchemas {\n nodes {\n id\n endpoint\n service\n createdAt\n updatedAt\n }\n }\n parentGraphQLSchemaId\n salesforceSchema {\n id\n createdAt\n updatedAt\n }\n services {\n slug\n }\n updatedAt\n createdAt\n appId\n }\n }\n }\n}",
operationName: "CreateGraphQLSchemaMutation",

@@ -185,0 +185,0 @@ variables: variables,

@@ -44,2 +44,6 @@ import { DocumentNode } from "graphql";

export declare function typeScriptForGraphQLType(schema: GraphQLSchema, gqlType: GraphQLType): string;
export declare const guessVariableDescriptions: (schema: GraphQLSchema, operationDefinition: OperationDefinitionNode, variableNames: string[]) => Record<string, {
usageCount: number;
descriptions?: Set<string>;
}>;
export declare function typeScriptSignatureForOperationVariables(variableNames: Array<string>, schema: GraphQLSchema, operationDefinition: OperationDefinitionNode): string;

@@ -46,0 +50,0 @@ export declare function listCount(gqlType: any): number;

@@ -23,3 +23,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPersistableOperation = exports.gatherHardcodedValues = exports.normalizeOperationsDoc = exports.formElComponent = exports.remixFormInput = exports.formInput = exports.patchSubscriptionWebhookSecretField = exports.patchSubscriptionWebhookField = exports.typeScriptTypeNameForOperation = exports.typeScriptSignatureForFragment = exports.typeScriptDefinitionObjectForFragment = exports.typeScriptSignatureForOperation = exports.typeScriptDefinitionObjectForOperation = exports.listCount = exports.typeScriptSignatureForOperationVariables = exports.typeScriptForGraphQLType = exports.gatherVariableDefinitions = exports.gatherAllReferencedTypes = void 0;
exports.extractPersistableOperation = exports.gatherHardcodedValues = exports.normalizeOperationsDoc = exports.formElComponent = exports.remixFormInput = exports.formInput = exports.patchSubscriptionWebhookSecretField = exports.patchSubscriptionWebhookField = exports.typeScriptTypeNameForOperation = exports.typeScriptSignatureForFragment = exports.typeScriptDefinitionObjectForFragment = exports.typeScriptSignatureForOperation = exports.typeScriptDefinitionObjectForOperation = exports.listCount = exports.typeScriptSignatureForOperationVariables = exports.guessVariableDescriptions = exports.typeScriptForGraphQLType = exports.gatherVariableDefinitions = exports.gatherAllReferencedTypes = void 0;
var graphql_1 = require("graphql");

@@ -123,2 +123,58 @@ var internalConsole_1 = require("./internalConsole");

exports.typeScriptForGraphQLType = typeScriptForGraphQLType;
var guessVariableDescriptions = function (schema, operationDefinition, variableNames) {
var variableRecords = {};
for (var _i = 0, variableNames_1 = variableNames; _i < variableNames_1.length; _i++) {
var variableName = variableNames_1[_i];
variableRecords[variableName] = {
usageCount: 0,
descriptions: new Set(),
};
}
var typeInfo = new graphql_1.TypeInfo(schema);
var argHandler = function (node) {
var _a;
if (node.value && node.value.kind === graphql_1.Kind.VARIABLE) {
var argument = typeInfo.getArgument();
var existingRecord = variableRecords[node.value.name.value];
var existingDescription = existingRecord === null || existingRecord === void 0 ? void 0 : existingRecord.descriptions;
if (existingDescription && (argument === null || argument === void 0 ? void 0 : argument.description)) {
existingDescription.add(argument.description);
}
if (!existingRecord) {
internalConsole_1.internalConsole.warn("Undefined variable $" + node.value.name.value + " found in operation " + ((_a = operationDefinition.name) === null || _a === void 0 ? void 0 : _a.value));
return node;
}
variableRecords[node.value.name.value] = __assign(__assign({}, existingRecord), { usageCount: (existingRecord === null || existingRecord === void 0 ? void 0 : existingRecord.usageCount) + 1 });
}
return node;
};
var objectFieldHandler = function (node) {
var _a;
if (node.value && node.value.kind === graphql_1.Kind.VARIABLE) {
var parentType = typeInfo.getParentInputType();
var namedParentType = (0, graphql_1.getNamedType)(parentType);
var field = void 0;
if ((0, graphql_1.isInputObjectType)(namedParentType)) {
field = namedParentType === null || namedParentType === void 0 ? void 0 : namedParentType.getFields()[node.name.value];
var existingRecord = variableRecords[node.value.name.value];
var existingDescription = existingRecord === null || existingRecord === void 0 ? void 0 : existingRecord.descriptions;
if (existingDescription && (field === null || field === void 0 ? void 0 : field.description)) {
existingDescription.add(field.description);
}
if (!existingRecord) {
internalConsole_1.internalConsole.warn("Undefined variable $" + node.value.name.value + " found in operation " + ((_a = operationDefinition.name) === null || _a === void 0 ? void 0 : _a.value));
return node;
}
variableRecords[node.value.name.value] = __assign(__assign({}, existingRecord), { usageCount: existingRecord.usageCount + 1 });
}
return node;
}
};
(0, graphql_1.visit)(operationDefinition, (0, graphql_1.visitWithTypeInfo)(typeInfo, {
Argument: argHandler,
ObjectField: objectFieldHandler,
}));
return variableRecords;
};
exports.guessVariableDescriptions = guessVariableDescriptions;
function typeScriptSignatureForOperationVariables(variableNames, schema, operationDefinition) {

@@ -139,58 +195,3 @@ var helper = function (variableDefinition) {

});
var guessVariableDescription = function (variableNames) {
var variableRecords = {};
for (var _i = 0, variableNames_1 = variableNames; _i < variableNames_1.length; _i++) {
var variableName = variableNames_1[_i];
variableRecords[variableName] = {
usageCount: 0,
descriptions: new Set(),
};
}
var typeInfo = new graphql_1.TypeInfo(schema);
var argHandler = function (node) {
var _a;
if (node.value && node.value.kind === graphql_1.Kind.VARIABLE) {
var argument = typeInfo.getArgument();
var existingRecord = variableRecords[node.value.name.value];
var existingDescription = existingRecord === null || existingRecord === void 0 ? void 0 : existingRecord.descriptions;
if (existingDescription && (argument === null || argument === void 0 ? void 0 : argument.description)) {
existingDescription.add(argument.description);
}
if (!existingRecord) {
internalConsole_1.internalConsole.warn("Undefined variable $" + node.value.name.value + " found in operation " + ((_a = operationDefinition.name) === null || _a === void 0 ? void 0 : _a.value));
return node;
}
variableRecords[node.value.name.value] = __assign(__assign({}, existingRecord), { usageCount: (existingRecord === null || existingRecord === void 0 ? void 0 : existingRecord.usageCount) + 1 });
}
return node;
};
var objectFieldHandler = function (node) {
var _a;
if (node.value && node.value.kind === graphql_1.Kind.VARIABLE) {
var parentType = typeInfo.getParentInputType();
var namedParentType = (0, graphql_1.getNamedType)(parentType);
var field = void 0;
if ((0, graphql_1.isInputObjectType)(namedParentType)) {
field = namedParentType === null || namedParentType === void 0 ? void 0 : namedParentType.getFields()[node.name.value];
var existingRecord = variableRecords[node.value.name.value];
var existingDescription = existingRecord === null || existingRecord === void 0 ? void 0 : existingRecord.descriptions;
if (existingDescription && (field === null || field === void 0 ? void 0 : field.description)) {
existingDescription.add(field.description);
}
if (!existingRecord) {
internalConsole_1.internalConsole.warn("Undefined variable $" + node.value.name.value + " found in operation " + ((_a = operationDefinition.name) === null || _a === void 0 ? void 0 : _a.value));
return node;
}
variableRecords[node.value.name.value] = __assign(__assign({}, existingRecord), { usageCount: existingRecord.usageCount + 1 });
}
return node;
}
};
(0, graphql_1.visit)(operationDefinition, (0, graphql_1.visitWithTypeInfo)(typeInfo, {
Argument: argHandler,
ObjectField: objectFieldHandler,
}));
return variableRecords;
};
var variableUsageInfo = guessVariableDescription(variableNames);
var variableUsageInfo = (0, exports.guessVariableDescriptions)(schema, operationDefinition, variableNames);
var typesObject = variables

@@ -197,0 +198,0 @@ .map(function (_a) {

import { DocumentNode, FragmentDefinitionNode, GraphQLSchema, OperationDefinitionNode, OperationTypeNode } from "graphql";
import { ExportedFile, FrameworkGenerator } from "./codegen/codegenHelpers";
export declare type EnabledService = {
enabled: boolean;
};
export declare type NetlifyGraphJson = {
enabledServices: EnabledService[];
schema?: string;
};
export declare type State = {

@@ -4,0 +11,0 @@ set: (key: string, value?: any) => any;

@@ -110,6 +110,6 @@ "use strict";

var generatedNetlifyGraphDynamicClient = function (netlifyGraphConfig) {
return lruCacheImplementation + "\n\n" + out(netlifyGraphConfig, ["node"], "const httpFetch = (siteId, options) => {\n const reqBody = options.body || null\n const userHeaders = options.headers || {}\n const headers = {\n ...userHeaders,\n 'Content-Type': 'application/json',\n 'Content-Length': reqBody.length,\n }\n\n const timeoutMs = 30_000\n\n const reqOptions = {\n method: 'POST',\n headers: headers,\n timeout: timeoutMs,\n }\n\n const url = 'https://graph.netlify.com/graphql?app_id=' + siteId\n\n const respBody = []\n\n return new Promise((resolve, reject) => {\n const req = https.request(url, reqOptions, (res) => {\n if (res.statusCode && (res.statusCode < 200 || res.statusCode > 299)) {\n return reject(\n new Error(\n \"Netlify Graph return non-OK HTTP status code\" + res.statusCode,\n ),\n )\n }\n\n res.on('data', (chunk) => respBody.push(chunk))\n\n res.on('end', () => {\n const resString = buffer.Buffer.concat(respBody).toString()\n resolve(resString)\n })\n })\n\n req.on('error', (error) => {\n console.error('Error making request to Netlify Graph:', error)\n })\n\n req.on('timeout', () => {\n req.destroy()\n reject(new Error('Request to Netlify Graph timed out'))\n })\n\n req.write(reqBody)\n req.end()\n })\n}\n") + "\n" + out(netlifyGraphConfig, ["browser"], "const httpFetch = (siteId, options) => {\n const reqBody = options.body || null;\n const userHeaders = options.headers || {};\n const headers = {\n ...userHeaders,\n 'Content-Type': 'application/json',\n };\n\n const timeoutMs = 30_000;\n\n const reqOptions = {\n method: 'POST',\n headers: headers,\n timeout: timeoutMs,\n body: reqBody\n };\n\n const url = 'https://graph.netlify.com/graphql?app_id=' + siteId;\n\n return fetch(url, reqOptions);\n}") + "\n\nconst fetchNetlifyGraph = function fetchNetlifyGraph(input) {\n const query = input.query;\n const docId = input.doc_id;\n const operationName = input.operationName;\n const variables = input.variables;\n\n const options = input.options || {};\n const accessToken = options.accessToken;\n const siteId = options.siteId || process.env.SITE_ID;\n\n const payload = {\n query: query,\n doc_id: docId,\n variables: variables,\n operationName: operationName,\n };\n\n let cachedOrLiveValue = new Promise((resolve) => {\n const cacheKey = calculateCacheKey(payload);\n\n // Check the cache for a previous result\n const cachedResultPair = getFromCache(cache, cacheKey);\n\n let conditionalHeaders = {\n 'If-None-Match': ''\n };\n let cachedResultValue;\n\n if (cachedResultPair) {\n const [etag, previousResult] = cachedResultPair;\n conditionalHeaders = {\n 'If-None-Match': etag\n };\n cachedResultValue = previousResult;\n }\n\n const response = httpFetch(siteId, {\n method: 'POST',\n headers: {\n ...conditionalHeaders,\n Authorization: accessToken ? 'Bearer ' + accessToken : '',\n },\n body: JSON.stringify(payload),\n });\n\n response.then((result) => {\n // Check response headers for a 304 Not Modified\n if (result.status === 304) {\n // Return the cached result\n resolve(cachedResultValue);\n }\n else if (result.status === 200) {\n // Update the cache with the new etag and result\n const etag = result.headers.get('etag');\n const resultJson = result.json();\n resultJson.then((json) => {\n if (etag) {\n // Make a not of the new etag for the given payload\n setInCache(cache, cacheKey, [etag, json])\n };\n resolve(json);\n });\n } else {\n return result.json().then((json) => {\n resolve(json);\n });\n }\n });\n });\n\n return cachedOrLiveValue\n}\n";
return lruCacheImplementation + "\n\n" + out(netlifyGraphConfig, ["node"], "const httpFetch = (siteId, options) => {\n const reqBody = options.body || null\n const userHeaders = options.headers || {}\n const headers = {\n ...userHeaders,\n 'Content-Type': 'application/json',\n 'Content-Length': reqBody.length,\n }\n\n const timeoutMs = 30_000\n\n const reqOptions = {\n method: 'POST',\n headers: headers,\n timeout: timeoutMs,\n }\n\n const url = 'https://graph.netlify.com/graphql?app_id=' + siteId\n\n const respBody = []\n\n return new Promise((resolve, reject) => {\n const req = https.request(url, reqOptions, (res) => {\n if (res.statusCode && (res.statusCode < 200 || res.statusCode > 299)) {\n return reject(\n new Error(\n \"Netlify Graph return non-OK HTTP status code\" + res.statusCode,\n ),\n )\n }\n\n res.on('data', (chunk) => respBody.push(chunk))\n\n res.on('end', () => {\n const resString = buffer.Buffer.concat(respBody).toString()\n resolve(resString)\n })\n })\n\n req.on('error', (error) => {\n console.error('Error making request to Netlify Graph:', error)\n })\n\n req.on('timeout', () => {\n req.destroy()\n reject(new Error('Request to Netlify Graph timed out'))\n })\n\n req.write(reqBody)\n req.end()\n })\n}\n") + "\n" + out(netlifyGraphConfig, ["browser"], "const httpFetch = (siteId, options) => {\n const reqBody = options.body || null;\n const userHeaders = options.headers || {};\n const headers = {\n ...userHeaders,\n 'Content-Type': 'application/json',\n };\n\n const timeoutMs = 30_000;\n\n const reqOptions = {\n method: 'POST',\n headers: headers,\n timeout: timeoutMs,\n body: reqBody\n };\n\n const url = 'https://graph.netlify.com/graphql?app_id=' + siteId;\n\n return fetch(url, reqOptions);\n}") + "\n\nconst fetchNetlifyGraph = function fetchNetlifyGraph(input) {\n const query = input.query;\n const docId = input.doc_id;\n const operationName = input.operationName;\n const variables = input.variables;\n\n const options = input.options || {};\n const accessToken = options.accessToken;\n const siteId = options.siteId || process.env.SITE_ID;\n\n const payload = {\n query: query,\n doc_id: docId,\n variables: variables,\n operationName: operationName,\n };\n\n let cachedOrLiveValue = new Promise((resolve) => {\n const cacheKey = calculateCacheKey(payload);\n\n // Check the cache for a previous result\n const cachedResultPair = getFromCache(cache, cacheKey);\n\n let conditionalHeaders = {\n 'If-None-Match': ''\n };\n let cachedResultValue;\n\n if (cachedResultPair) {\n const [etag, previousResult] = cachedResultPair;\n conditionalHeaders = {\n 'If-None-Match': etag\n };\n cachedResultValue = previousResult;\n }\n\n const response = httpFetch(siteId, {\n method: 'POST',\n headers: {\n ...conditionalHeaders,\n Authorization: accessToken ? 'Bearer ' + accessToken : '',\n },\n body: JSON.stringify(payload),\n });\n\n response.then((result) => {\n // Check response headers for a 304 Not Modified\n if (result.status === 304) {\n // Return the cached result\n resolve(cachedResultValue);\n }\n else if (result.status === 200) {\n // Update the cache with the new etag and result\n const etag = result.headers.get('etag');\n const resultJson = result.json();\n resultJson.then((json) => {\n if (etag) {\n // Make a note of the new etag for the given payload\n setInCache(cache, cacheKey, [etag, json])\n };\n resolve(json);\n });\n } else {\n return result.json().then((json) => {\n resolve(json);\n });\n }\n });\n });\n\n return cachedOrLiveValue\n}\n";
};
var generatedNetlifyGraphPersistedClient = function (netlifyGraphConfig, schemaId) {
return lruCacheImplementation + "\n\n" + out(netlifyGraphConfig, ["node"], "const httpGet = (input) => {\n const userHeaders = input.headers || {};\n const fullHeaders = {\n ...userHeaders,\n 'Content-Type': 'application/json'\n };\n const timeoutMs = 30_000\n const reqOptions = {\n method: 'GET',\n headers: fullHeaders,\n timeout: timeoutMs,\n };\n\n if (!input.docId) {\n throw new Error('docId is required for GET requests: ' + input.operationName);\n }\n\n const schemaId = input.schemaId || " + (schemaId ? "\"" + schemaId + "\"" : "undefined") + ";\n\n const encodedVariables = encodeURIComponent(input.variables || \"null\");\n const url = 'https://graph.netlify.com/graphql?app_id=' + input.siteId + '&doc_id=' + input.docId + (input.operationName ? ('&operationName=' + input.operationName) : '') + (schemaId ? ('&schemaId=' + schemaId) : '') + '&variables=' + encodedVariables;\n \n const respBody = []\n\n return new Promise((resolve, reject) => {\n const req = https.request(url, reqOptions, (res) => {\n if (res.statusCode && (res.statusCode < 200 || res.statusCode > 299)) {\n return reject(\n new Error(\n \"Netlify Graph return non-OK HTTP status code\" + res.statusCode,\n ),\n )\n }\n\n res.on('data', (chunk) => respBody.push(chunk))\n\n res.on('end', () => {\n const resString = buffer.Buffer.concat(respBody).toString()\n resolve(resString)\n })\n })\n\n req.on('error', (error) => {\n console.error('Error making request to Netlify Graph:', error)\n })\n\n req.on('timeout', () => {\n req.destroy()\n reject(new Error('Request to Netlify Graph timed out'))\n })\n\n req.end()\n })\n}\n\nconst httpPost = (input) => {\n const reqBody = input.body || null\n const userHeaders = input.headers || {}\n const headers = {\n ...userHeaders,\n 'Content-Type': 'application/json',\n 'Content-Length': reqBody.length,\n }\n\n const timeoutMs = 30_000\n\n const reqOptions = {\n method: 'POST',\n headers: headers,\n timeout: timeoutMs,\n }\n\n const schemaId = input.schemaId || " + (schemaId ? "\"" + schemaId + "\"" : "undefined") + ";\n\n\n const url = 'https://graph.netlify.com/graphql?app_id=' + input.siteId +\n (schemaId ? ('&schemaId=' + schemaId) : '');\n const respBody = []\n\n return new Promise((resolve, reject) => {\n const req = https.request(url, reqOptions, (res) => {\n if (res.statusCode && (res.statusCode < 200 || res.statusCode > 299)) {\n return reject(\n new Error(\n \"Netlify Graph return non-OK HTTP status code\" + res.statusCode,\n ),\n )\n }\n\n res.on('data', (chunk) => respBody.push(chunk))\n\n res.on('end', () => {\n const resString = buffer.Buffer.concat(respBody).toString()\n resolve(resString)\n })\n })\n\n req.on('error', (error) => {\n console.error('Error making request to Netlify Graph:', error)\n })\n\n req.on('timeout', () => {\n req.destroy()\n reject(new Error('Request to Netlify Graph timed out'))\n })\n\n req.write(reqBody)\n req.end()\n })\n}") + "\n\n" + out(netlifyGraphConfig, ["browser"], "const httpGet = (input) => {\n const userHeaders = input.headers || {};\n const fullHeaders = {\n ...userHeaders,\n 'Content-Type': 'application/json',\n };\n\n const timeoutMs = 30_000;\n\n const reqOptions = {\n method: 'GET',\n headers: fullHeaders,\n timeout: timeoutMs,\n };\n\n const encodedVariables = encodeURIComponent(\n JSON.stringify(input.variables || null)\n );\n\n const schemaId = input.schemaId || " + (schemaId ? "\"" + schemaId + "\"" : "undefined") + ";\n\n const url =\n 'https://graph.netlify.com/graphql?app_id=' +\n input.siteId +\n '&doc_id=' +\n input.docId +\n (input.operationName ? '&operationName=' + input.operationName : '') +\n (schemaId ? ('&schemaId=' + schemaId) : '') +\n '&variables=' +\n encodedVariables;\n\n return fetch(url, reqOptions).then((response) => response.text());\n};\n\nconst httpPost = (input) => {\n const userHeaders = input.headers || {};\n const fullHeaders = {\n ...userHeaders,\n 'Content-Type': 'application/json',\n };\n\n const reqBody = JSON.stringify({\n doc_id: input.docId,\n query: input.query,\n operationName: input.operationName,\n variables: input.variables,\n });\n\n const timeoutMs = 30_000;\n\n const reqOptions = {\n method: 'POST',\n headers: fullHeaders,\n timeout: timeoutMs,\n body: reqBody,\n };\n\n const schemaId = input.schemaId || " + (schemaId ? "\"" + schemaId + "\"" : "undefined") + ";\n\n const url = 'https://graph.netlify.com/graphql?app_id=' + input.siteId +\n (schemaId ? ('&schemaId=' + schemaId) : '');\n\n return fetch(url, reqOptions);\n};") + "\n\nconst fetchNetlifyGraph = function fetchNetlifyGraph(input) {\n const docId = input.doc_id;\n const operationName = input.operationName;\n const variables = input.variables;\n\n const options = input.options || {};\n const accessToken = options.accessToken;\n const siteId = options.siteId || process.env.SITE_ID;\n\n const httpMethod = input.fetchStrategy === 'GET' ? httpGet : httpPost;\n\n let response;\n\n if (input.fetchStrategy === 'GET') {\n response = httpMethod({\n siteId: siteId,\n docId: docId,\n query: input.query,\n headers: {\n Authorization: accessToken ? 'Bearer ' + accessToken : '',\n },\n variables: variables,\n operationName: operationName,\n }).then((result) => JSON.parse(result));\n } else {\n const payload = {\n query: input.query,\n doc_id: docId,\n variables: variables,\n operationName: operationName,\n };\n\n let cachedOrLiveValue = new Promise((resolve) => {\n const cacheKey = calculateCacheKey(payload);\n\n // Check the cache for a previous result\n const cachedResultPair = getFromCache(cache, cacheKey);\n\n let conditionalHeaders = {\n 'If-None-Match': ''\n };\n let cachedResultValue;\n\n if (cachedResultPair) {\n const [etag, previousResult] = cachedResultPair;\n conditionalHeaders = {\n 'If-None-Match': etag\n };\n cachedResultValue = previousResult;\n }\n\n const persistedResponse = httpMethod({\n siteId: siteId,\n docId: docId,\n query: input.query,\n headers: {\n ...conditionalHeaders,\n Authorization: accessToken ? 'Bearer ' + accessToken : '',\n },\n variables: variables,\n operationName: operationName,\n });\n\n persistedResponse.then((result) => {\n // Check response headers for a 304 Not Modified\n if (result.status === 304) {\n // Return the cached result\n resolve(cachedResultValue);\n }\n else if (result.status === 200) {\n // Update the cache with the new etag and result\n const etag = result.headers.get('etag');\n const resultJson = result.json();\n resultJson.then((json) => {\n if (etag) {\n // Make a not of the new etag for the given payload\n setInCache(cache, cacheKey, [etag, json])\n };\n resolve(json);\n });\n } else {\n return result.json().then((json) => {\n resolve(json);\n });\n }\n });\n });\n\n response = cachedOrLiveValue;\n }\n\n return response;\n};\n";
return lruCacheImplementation + "\n\n" + out(netlifyGraphConfig, ["node"], "const httpGet = (input) => {\n const userHeaders = input.headers || {};\n const fullHeaders = {\n ...userHeaders,\n 'Content-Type': 'application/json'\n };\n const timeoutMs = 30_000\n const reqOptions = {\n method: 'GET',\n headers: fullHeaders,\n timeout: timeoutMs,\n };\n\n if (!input.docId) {\n throw new Error('docId is required for GET requests: ' + input.operationName);\n }\n\n const schemaId = input.schemaId || " + (schemaId ? "\"" + schemaId + "\"" : "undefined") + ";\n\n const encodedVariables = encodeURIComponent(input.variables || \"null\");\n const url = 'https://graph.netlify.com/graphql?app_id=' + input.siteId + '&doc_id=' + input.docId + (input.operationName ? ('&operationName=' + input.operationName) : '') + (schemaId ? ('&schemaId=' + schemaId) : '') + '&variables=' + encodedVariables;\n \n const respBody = []\n\n return new Promise((resolve, reject) => {\n const req = https.request(url, reqOptions, (res) => {\n if (res.statusCode && (res.statusCode < 200 || res.statusCode > 299)) {\n return reject(\n new Error(\n \"Netlify Graph return non-OK HTTP status code\" + res.statusCode,\n ),\n )\n }\n\n res.on('data', (chunk) => respBody.push(chunk))\n\n res.on('end', () => {\n const resString = buffer.Buffer.concat(respBody).toString()\n resolve(resString)\n })\n })\n\n req.on('error', (error) => {\n console.error('Error making request to Netlify Graph:', error)\n })\n\n req.on('timeout', () => {\n req.destroy()\n reject(new Error('Request to Netlify Graph timed out'))\n })\n\n req.end()\n })\n}\n\nconst httpPost = (input) => {\n const reqBody = input.body || null\n const userHeaders = input.headers || {}\n const headers = {\n ...userHeaders,\n 'Content-Type': 'application/json',\n 'Content-Length': reqBody.length,\n }\n\n const timeoutMs = 30_000\n\n const reqOptions = {\n method: 'POST',\n headers: headers,\n timeout: timeoutMs,\n }\n\n const schemaId = input.schemaId || " + (schemaId ? "\"" + schemaId + "\"" : "undefined") + ";\n\n\n const url = 'https://graph.netlify.com/graphql?app_id=' + input.siteId +\n (schemaId ? ('&schemaId=' + schemaId) : '');\n const respBody = []\n\n return new Promise((resolve, reject) => {\n const req = https.request(url, reqOptions, (res) => {\n if (res.statusCode && (res.statusCode < 200 || res.statusCode > 299)) {\n return reject(\n new Error(\n \"Netlify Graph return non-OK HTTP status code\" + res.statusCode,\n ),\n )\n }\n\n res.on('data', (chunk) => respBody.push(chunk))\n\n res.on('end', () => {\n const resString = buffer.Buffer.concat(respBody).toString()\n resolve(resString)\n })\n })\n\n req.on('error', (error) => {\n console.error('Error making request to Netlify Graph:', error)\n })\n\n req.on('timeout', () => {\n req.destroy()\n reject(new Error('Request to Netlify Graph timed out'))\n })\n\n req.write(reqBody)\n req.end()\n })\n}") + "\n\n" + out(netlifyGraphConfig, ["browser"], "const httpGet = (input) => {\n const userHeaders = input.headers || {};\n const fullHeaders = {\n ...userHeaders,\n 'Content-Type': 'application/json',\n };\n\n const timeoutMs = 30_000;\n\n const reqOptions = {\n method: 'GET',\n headers: fullHeaders,\n timeout: timeoutMs,\n };\n\n const encodedVariables = encodeURIComponent(\n JSON.stringify(input.variables || null)\n );\n\n const schemaId = input.schemaId || " + (schemaId ? "\"" + schemaId + "\"" : "undefined") + ";\n\n const url =\n 'https://graph.netlify.com/graphql?app_id=' +\n input.siteId +\n '&doc_id=' +\n input.docId +\n (input.operationName ? '&operationName=' + input.operationName : '') +\n (schemaId ? ('&schemaId=' + schemaId) : '') +\n '&variables=' +\n encodedVariables;\n\n return fetch(url, reqOptions).then((response) => response.text());\n};\n\nconst httpPost = (input) => {\n const userHeaders = input.headers || {};\n const fullHeaders = {\n ...userHeaders,\n 'Content-Type': 'application/json',\n };\n\n const reqBody = JSON.stringify({\n doc_id: input.docId,\n query: input.query,\n operationName: input.operationName,\n variables: input.variables,\n });\n\n const timeoutMs = 30_000;\n\n const reqOptions = {\n method: 'POST',\n headers: fullHeaders,\n timeout: timeoutMs,\n body: reqBody,\n };\n\n const schemaId = input.schemaId || " + (schemaId ? "\"" + schemaId + "\"" : "undefined") + ";\n\n const url = 'https://graph.netlify.com/graphql?app_id=' + input.siteId +\n (schemaId ? ('&schemaId=' + schemaId) : '');\n\n return fetch(url, reqOptions);\n};") + "\n\nconst fetchNetlifyGraph = function fetchNetlifyGraph(input) {\n const docId = input.doc_id;\n const operationName = input.operationName;\n const variables = input.variables;\n\n const options = input.options || {};\n const accessToken = options.accessToken;\n const siteId = options.siteId || process.env.SITE_ID;\n\n const httpMethod = input.fetchStrategy === 'GET' ? httpGet : httpPost;\n\n let response;\n\n if (input.fetchStrategy === 'GET') {\n response = httpMethod({\n siteId: siteId,\n docId: docId,\n query: input.query,\n headers: {\n Authorization: accessToken ? 'Bearer ' + accessToken : '',\n },\n variables: variables,\n operationName: operationName,\n }).then((result) => JSON.parse(result));\n } else {\n const payload = {\n query: input.query,\n doc_id: docId,\n variables: variables,\n operationName: operationName,\n };\n\n let cachedOrLiveValue = new Promise((resolve) => {\n const cacheKey = calculateCacheKey(payload);\n\n // Check the cache for a previous result\n const cachedResultPair = getFromCache(cache, cacheKey);\n\n let conditionalHeaders = {\n 'If-None-Match': ''\n };\n let cachedResultValue;\n\n if (cachedResultPair) {\n const [etag, previousResult] = cachedResultPair;\n conditionalHeaders = {\n 'If-None-Match': etag\n };\n cachedResultValue = previousResult;\n }\n\n const persistedResponse = httpMethod({\n siteId: siteId,\n docId: docId,\n query: input.query,\n headers: {\n ...conditionalHeaders,\n Authorization: accessToken ? 'Bearer ' + accessToken : '',\n },\n variables: variables,\n operationName: operationName,\n });\n\n persistedResponse.then((result) => {\n // Check response headers for a 304 Not Modified\n if (result.status === 304) {\n // Return the cached result\n resolve(cachedResultValue);\n }\n else if (result.status === 200) {\n // Update the cache with the new etag and result\n const etag = result.headers.get('etag');\n const resultJson = result.json();\n resultJson.then((json) => {\n if (etag) {\n // Make a note of the new etag for the given payload\n setInCache(cache, cacheKey, [etag, json])\n };\n resolve(json);\n });\n } else {\n return result.json().then((json) => {\n resolve(json);\n });\n }\n });\n });\n\n response = cachedOrLiveValue;\n }\n\n return response;\n};\n";
};

@@ -116,0 +116,0 @@ var subscriptionParserReturnName = function (fn) {

import GeneratedClient from "./generatedOneGraphClient";
import type { CreateNewSchemaMutationInput } from "./generatedOneGraphClient";
/**
* Fetch a schema (in json form) for an app by its schemaId
* @param {object} input
* @param {string} input.appId
* @param {string} input.schemaId
* @param {string} input.accessToken
* @returns {Promise<Record<string, any>>} The schema json
*/
export declare const fetchOneGraphSchemaByIdJson: ({ appId, schemaId, accessToken, }: {
appId: string;
schemaId: string;
accessToken: string;
}) => Promise<any>;
/**
* Fetch a schema and parse it for an app by its schemaId
* @param {object} input
* @param {string} input.siteId
* @param {string} input.schemaId
* @param {string} input.accessToken
* @returns {Promise<GraphQLSchema>} The schema for the app
*/
export declare const fetchOneGraphSchemaById: ({ siteId, schemaId, accessToken, }: {
siteId: string;
schemaId: string;
accessToken: string;
}) => Promise<import("graphql").GraphQLSchema>;
/**
* Given an appId and desired services, fetch the schema (in json form) for that app

@@ -8,3 +35,3 @@ * @param {string} appId

*/
export declare const fetchOneGraphSchemaJson: (appId: string, enabledServices: string[]) => Promise<any>;
export declare const fetchOneGraphSchemaForServicesJson: (appId: string, enabledServices: string[]) => Promise<any>;
/**

@@ -16,3 +43,3 @@ * Given an appId and desired services, fetch the schema json for an app and parse it into a GraphQL Schema

*/
export declare const fetchOneGraphSchema: (appId: string, enabledServices: string[]) => Promise<import("graphql").GraphQLSchema>;
export declare const fetchOneGraphSchemaForServices: (appId: string, enabledServices: string[]) => Promise<import("graphql").GraphQLSchema>;
export declare type PersistedQuery = {

@@ -138,21 +165,4 @@ id: string;

* Fetch the schema metadata for a site (enabled services, id, etc.)
* @param {string} authToken The (typically netlify) access token that is used for authentication, if any
* @param {string} siteId The site id to query against
* @returns {Promise<object|undefined>} The schema metadata for the site
*/
export declare const fetchAppSchema: (authToken: string, siteId: string) => Promise<{
appId: string;
createdAt: string;
id: string;
services: {
friendlyServiceName: string;
logoUrl: string;
service: "ADROLL" | "ASANA" | "BOX" | "CONTENTFUL" | "DEV_TO" | "DOCUSIGN" | "DRIBBBLE" | "DROPBOX" | "EGGHEADIO" | "EVENTIL" | "FACEBOOK" | "FIREBASE" | "GITHUB" | "GMAIL" | "GONG" | "GOOGLE" | "GOOGLE_ADS" | "GOOGLE_ANALYTICS" | "GOOGLE_CALENDAR" | "GOOGLE_COMPUTE" | "GOOGLE_DOCS" | "GOOGLE_SEARCH_CONSOLE" | "GOOGLE_TRANSLATE" | "HUBSPOT" | "INTERCOM" | "MAILCHIMP" | "MEETUP" | "NETLIFY" | "NOTION" | "OUTREACH" | "PRODUCT_HUNT" | "QUICKBOOKS" | "SALESFORCE" | "SANITY" | "SLACK" | "SPOTIFY" | "STRIPE" | "TRELLO" | "TWILIO" | "TWITTER" | "TWITCH_TV" | "YNAB" | "YOUTUBE" | "ZEIT" | "ZENDESK" | "AIRTABLE" | "APOLLO" | "BREX" | "BUNDLEPHOBIA" | "CHARGEBEE" | "CLEARBIT" | "CLOUDFLARE" | "CRUNCHBASE" | "DESCURI" | "FEDEX" | "GOOGLE_MAPS" | "GRAPHCMS" | "IMMIGRATION_GRAPH" | "LOGDNA" | "MIXPANEL" | "MUX" | "NPM" | "ONEGRAPH" | "ORBIT" | "OPEN_COLLECTIVE" | "RSS" | "UPS" | "USPS" | "WORDPRESS";
slug: string;
supportsCustomRedirectUri: boolean;
supportsCustomServiceAuth: boolean;
supportsOauthLogin: boolean;
}[];
updatedAt: string;
}>;
export declare const fetchAppSchemaQuery: typeof GeneratedClient.fetchAppSchemaQuery;
/**

@@ -180,3 +190,3 @@ * If a site does not exists upstream in OneGraph for the given site, create it

*/
export declare const createNewAppSchema: (nfToken: string, input: any) => Promise<{
export declare const createNewAppSchema: (nfToken: string, input: CreateNewSchemaMutationInput["input"]) => Promise<{
id: string;

@@ -183,0 +193,0 @@ services: {

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(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 __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -39,3 +50,3 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchListNetlifyEnabledServicesQuery = exports.fetchSharedDocumentQuery = exports.executeCreateSharedDocumentMutation = exports.fetchListSharedDocumentsQuery = exports.executeCreateGraphQLSchemaMutation = exports.executeCreateApiTokenMutation = exports.executeMarkCliSessionInactive = exports.executeMarkCliSessionActiveHeartbeat = exports.fetchEnabledServices = exports.ensureAppForSite = exports.createNewAppSchema = exports.upsertAppForSite = exports.fetchAppSchema = exports.friendlyEventName = exports.executeCreatePersistedQueryMutation = exports.ackCLISessionEvents = exports.updateCLISessionMetadata = exports.createCLISession = exports.fetchCliSessionEvents = exports.fetchCliSession = exports.fetchPersistedQuery = exports.fetchOneGraphSchema = exports.fetchOneGraphSchemaJson = void 0;
exports.fetchListNetlifyEnabledServicesQuery = exports.fetchSharedDocumentQuery = exports.executeCreateSharedDocumentMutation = exports.fetchListSharedDocumentsQuery = exports.executeCreateGraphQLSchemaMutation = exports.executeCreateApiTokenMutation = exports.executeMarkCliSessionInactive = exports.executeMarkCliSessionActiveHeartbeat = exports.fetchEnabledServices = exports.ensureAppForSite = exports.createNewAppSchema = exports.upsertAppForSite = exports.fetchAppSchemaQuery = exports.friendlyEventName = exports.executeCreatePersistedQueryMutation = exports.ackCLISessionEvents = exports.updateCLISessionMetadata = exports.createCLISession = exports.fetchCliSessionEvents = exports.fetchCliSession = exports.fetchPersistedQuery = exports.fetchOneGraphSchemaForServices = exports.fetchOneGraphSchemaForServicesJson = exports.fetchOneGraphSchemaById = exports.fetchOneGraphSchemaByIdJson = void 0;
var graphql_1 = require("graphql");

@@ -45,6 +56,77 @@ var fetch = require("node-fetch");

var generatedOneGraphClient_1 = require("./generatedOneGraphClient");
// import type { CreateNewSchemaMutationInput } from "./generatedOneGraphClient";
var ONEDASH_APP_ID = "0b066ba6-ed39-4db8-a497-ba0be34d5b2a";
var netlifyGraphHost = "graph.netlify.com";
/**
* Fetch a schema (in json form) for an app by its schemaId
* @param {object} input
* @param {string} input.appId
* @param {string} input.schemaId
* @param {string} input.accessToken
* @returns {Promise<Record<string, any>>} The schema json
*/
var fetchOneGraphSchemaByIdJson = function (_a) {
var appId = _a.appId, schemaId = _a.schemaId, accessToken = _a.accessToken;
return __awaiter(void 0, void 0, void 0, function () {
var url, authorizationHeader, headers, response, text, error_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
url = "https://" + netlifyGraphHost + "/schema?app_id=" + appId + "&schemaId=" + schemaId;
authorizationHeader = accessToken
? { authorization: "Bearer " + accessToken }
: {};
headers = __assign({}, authorizationHeader);
_b.label = 1;
case 1:
_b.trys.push([1, 4, , 5]);
return [4 /*yield*/, fetch(url, {
method: "GET",
headers: headers,
body: null,
})];
case 2:
response = _b.sent();
return [4 /*yield*/, response.text()];
case 3:
text = _b.sent();
return [2 /*return*/, JSON.parse(text)];
case 4:
error_1 = _b.sent();
internalConsole_1.internalConsole.error("Error fetching schema: " + JSON.stringify(error_1, null, 2));
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
});
};
exports.fetchOneGraphSchemaByIdJson = fetchOneGraphSchemaByIdJson;
/**
* Fetch a schema and parse it for an app by its schemaId
* @param {object} input
* @param {string} input.siteId
* @param {string} input.schemaId
* @param {string} input.accessToken
* @returns {Promise<GraphQLSchema>} The schema for the app
*/
var fetchOneGraphSchemaById = function (_a) {
var siteId = _a.siteId, schemaId = _a.schemaId, accessToken = _a.accessToken;
return __awaiter(void 0, void 0, void 0, function () {
var result, schema;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, (0, exports.fetchOneGraphSchemaByIdJson)({
accessToken: accessToken,
appId: siteId,
schemaId: schemaId,
})];
case 1:
result = _b.sent();
schema = (0, graphql_1.buildClientSchema)(result.data);
return [2 /*return*/, schema];
}
});
});
};
exports.fetchOneGraphSchemaById = fetchOneGraphSchemaById;
/**
* Given an appId and desired services, fetch the schema (in json form) for that app

@@ -55,4 +137,4 @@ * @param {string} appId

*/
var fetchOneGraphSchemaJson = function (appId, enabledServices) { return __awaiter(void 0, void 0, void 0, function () {
var url, headers, response, text, error_1;
var fetchOneGraphSchemaForServicesJson = function (appId, enabledServices) { return __awaiter(void 0, void 0, void 0, function () {
var url, headers, response, text, error_2;
return __generator(this, function (_a) {

@@ -78,4 +160,4 @@ switch (_a.label) {

case 4:
error_1 = _a.sent();
internalConsole_1.internalConsole.error("Error fetching schema: " + JSON.stringify(error_1, null, 2));
error_2 = _a.sent();
internalConsole_1.internalConsole.error("Error fetching schema: " + JSON.stringify(error_2, null, 2));
return [3 /*break*/, 5];

@@ -86,3 +168,3 @@ case 5: return [2 /*return*/];

}); };
exports.fetchOneGraphSchemaJson = fetchOneGraphSchemaJson;
exports.fetchOneGraphSchemaForServicesJson = fetchOneGraphSchemaForServicesJson;
/**

@@ -94,7 +176,7 @@ * Given an appId and desired services, fetch the schema json for an app and parse it into a GraphQL Schema

*/
var fetchOneGraphSchema = function (appId, enabledServices) { return __awaiter(void 0, void 0, void 0, function () {
var fetchOneGraphSchemaForServices = function (appId, enabledServices) { return __awaiter(void 0, void 0, void 0, function () {
var result, schema;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, (0, exports.fetchOneGraphSchemaJson)(appId, enabledServices)];
case 0: return [4 /*yield*/, (0, exports.fetchOneGraphSchemaForServicesJson)(appId, enabledServices)];
case 1:

@@ -107,3 +189,3 @@ result = _a.sent();

}); };
exports.fetchOneGraphSchema = fetchOneGraphSchema;
exports.fetchOneGraphSchemaForServices = fetchOneGraphSchemaForServices;
/**

@@ -310,24 +392,4 @@ * Fetch a persisted doc belonging to appId by its id

* Fetch the schema metadata for a site (enabled services, id, etc.)
* @param {string} authToken The (typically netlify) access token that is used for authentication, if any
* @param {string} siteId The site id to query against
* @returns {Promise<object|undefined>} The schema metadata for the site
*/
var fetchAppSchema = function (authToken, siteId) { return __awaiter(void 0, void 0, void 0, function () {
var result;
var _a, _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0: return [4 /*yield*/, generatedOneGraphClient_1.default.fetchAppSchemaQuery({
nfToken: authToken,
appId: siteId,
}, {
siteId: siteId,
})];
case 1:
result = _d.sent();
return [2 /*return*/, (_c = (_b = (_a = result.data) === null || _a === void 0 ? void 0 : _a.oneGraph) === null || _b === void 0 ? void 0 : _b.app) === null || _c === void 0 ? void 0 : _c.graphQLSchema];
}
});
}); };
exports.fetchAppSchema = fetchAppSchema;
exports.fetchAppSchemaQuery = generatedOneGraphClient_1.default.fetchAppSchemaQuery;
/**

@@ -363,4 +425,3 @@ * If a site does not exists upstream in OneGraph for the given site, create it

*/
var createNewAppSchema = function (nfToken, input //: CreateNewSchemaMutationInput["input"]
) { return __awaiter(void 0, void 0, void 0, function () {
var createNewAppSchema = function (nfToken, input) { return __awaiter(void 0, void 0, void 0, function () {
var result;

@@ -367,0 +428,0 @@ var _a, _b, _c;

{
"name": "netlify-onegraph-internal",
"version": "0.2.0",
"version": "0.2.1",
"description": "Internal tools for use by Netlify",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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