bigrequest
Version:
A typesafe, servelerless-friendly Node.js HTTP request client for the BigCommerce API
189 lines (183 loc) • 6.37 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// src/oauth.ts
var import_jose = require("jose");
var import_zod = require("zod");
// src/error.ts
var BigRequestError = class extends Error {
constructor(message) {
super(message);
this.name = "BigRequestError";
}
};
// src/oauth.ts
var oauthConfigSchema = import_zod.z.object({
clientId: import_zod.z.string().min(1),
clientSecret: import_zod.z.string().min(1),
authCallback: import_zod.z.string().url()
});
var oauth = (config) => {
const oauthConfig = oauthConfigSchema.safeParse(config);
if (!oauthConfig.success) {
throw new BigRequestError(
`Invalid OAuth config: ${JSON.stringify(oauthConfig.error.flatten().fieldErrors, null, 2)}`
);
}
const authCallbackQuerySchema = import_zod.z.object({
code: import_zod.z.string(),
scope: import_zod.z.string(),
context: import_zod.z.string()
});
const authorize = async (query) => {
const authCallbackQuery = authCallbackQuerySchema.safeParse(query);
if (!authCallbackQuery.success) {
throw new BigRequestError(
`Invalid Auth Callback arguments: ${JSON.stringify(
authCallbackQuery.error.flatten().fieldErrors,
null,
2
)}`
);
}
const oauthResponse = await fetch(`https://login.bigcommerce.com/oauth2/token`, {
method: "POST",
headers: {
accept: "application/json",
"content-type": "application/json"
},
body: JSON.stringify({
client_id: oauthConfig.data.clientId,
client_secret: oauthConfig.data.clientSecret,
code: authCallbackQuery.data.code,
context: authCallbackQuery.data.context,
scope: authCallbackQuery.data.scope,
grant_type: "authorization_code",
redirect_uri: oauthConfig.data.authCallback
})
});
const oauthResponseSchema = import_zod.z.object({
access_token: import_zod.z.string(),
scope: import_zod.z.string(),
user: import_zod.z.object({
id: import_zod.z.number(),
username: import_zod.z.string(),
email: import_zod.z.string()
}),
context: import_zod.z.string(),
account_uuid: import_zod.z.string()
});
const accessTokenResponse = oauthResponseSchema.safeParse(await oauthResponse.json());
if (!accessTokenResponse.success) {
throw new BigRequestError(
`Invalid access token response: ${JSON.stringify(
accessTokenResponse.error.flatten().fieldErrors,
null,
2
)}`
);
}
return accessTokenResponse.data;
};
const jwtSchema = import_zod.z.string().min(1);
const verify = async (signedPayloadJwt) => {
const parsedJwt = jwtSchema.safeParse(signedPayloadJwt);
if (!parsedJwt.success) {
throw new BigRequestError(
`Invalid signed payload JWT: ${JSON.stringify(
parsedJwt.error.flatten().fieldErrors,
null,
2
)}`
);
}
const secret = new TextEncoder().encode(oauthConfig.data.clientSecret);
const decoded = await (0, import_jose.jwtVerify)(parsedJwt.data, secret);
const verifiedJwtSchema = import_zod.z.object({
aud: import_zod.z.string(),
iss: import_zod.z.string(),
iat: import_zod.z.number(),
nbf: import_zod.z.number(),
exp: import_zod.z.number(),
jti: import_zod.z.string(),
sub: import_zod.z.string(),
user: import_zod.z.object({
id: import_zod.z.number(),
email: import_zod.z.string().email(),
locale: import_zod.z.string()
}),
owner: import_zod.z.object({
id: import_zod.z.number(),
email: import_zod.z.string().email()
}),
url: import_zod.z.string(),
channel_id: import_zod.z.number().nullable()
});
const parsedVerifiedJwt = verifiedJwtSchema.safeParse(decoded.payload);
if (!parsedVerifiedJwt.success) {
throw new BigRequestError(
`Verified JWT schema invalid: ${JSON.stringify(
parsedVerifiedJwt.error.flatten().fieldErrors,
null,
2
)}`
);
}
return parsedVerifiedJwt.data;
};
return {
authorize,
verify
};
};
// src/rest.ts
var import_openapi_fetch = __toESM(require("openapi-fetch"));
var import_zod2 = require("zod");
var restConfigSchema = import_zod2.z.object({
storeHash: import_zod2.z.string().min(1),
accessToken: import_zod2.z.string().min(1)
});
var rest = ({ storeHash, accessToken }) => {
const restConfig = restConfigSchema.safeParse({ storeHash, accessToken });
if (!restConfig.success) {
throw new BigRequestError(
`Invalid REST config: ${JSON.stringify(restConfig.error.flatten().fieldErrors, null, 2)}`
);
}
return {
v2: (0, import_openapi_fetch.default)({
baseUrl: `https://api.bigcommerce.com/stores/${restConfig.data.storeHash}/v2`,
headers: { "x-auth-token": restConfig.data.accessToken }
}),
v3: (0, import_openapi_fetch.default)({
baseUrl: `https://api.bigcommerce.com/stores/${restConfig.data.storeHash}/v3`,
headers: { "x-auth-token": restConfig.data.accessToken }
})
};
};
// src/index.ts
var bigrequest = {
oauth,
rest
};
module.exports = bigrequest;