planning
All checks were successful
Publish To Prod / deploy_and_publish (push) Successful in 35s

This commit is contained in:
2024-10-14 09:15:30 +02:00
parent bcba00a730
commit 6e64e138e2
21059 changed files with 2317811 additions and 1 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,613 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.API_NAME = void 0;
var _get2 = _interopRequireDefault(require("lodash/get"));
var _flow2 = _interopRequireDefault(require("lodash/flow"));
var _decapCmsLibUtil = require("decap-cms-lib-util");
var _path = require("path");
var _commonTags = require("common-tags");
var _whatTheDiff = require("what-the-diff");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var BitBucketPullRequestState = /*#__PURE__*/function (BitBucketPullRequestState) {
BitBucketPullRequestState["MERGED"] = "MERGED";
BitBucketPullRequestState["SUPERSEDED"] = "SUPERSEDED";
BitBucketPullRequestState["OPEN"] = "OPEN";
BitBucketPullRequestState["DECLINED"] = "DECLINED";
return BitBucketPullRequestState;
}(BitBucketPullRequestState || {});
var BitBucketPullRequestStatusState = /*#__PURE__*/function (BitBucketPullRequestStatusState) {
BitBucketPullRequestStatusState["Successful"] = "SUCCESSFUL";
BitBucketPullRequestStatusState["Failed"] = "FAILED";
BitBucketPullRequestStatusState["InProgress"] = "INPROGRESS";
BitBucketPullRequestStatusState["Stopped"] = "STOPPED";
return BitBucketPullRequestStatusState;
}(BitBucketPullRequestStatusState || {});
const API_NAME = exports.API_NAME = 'Bitbucket';
const APPLICATION_JSON = 'application/json; charset=utf-8';
function replace404WithEmptyResponse(err) {
if (err && err.status === 404) {
console.log('This 404 was expected and handled appropriately.');
return {
size: 0,
values: []
};
} else {
return Promise.reject(err);
}
}
class API {
constructor(config) {
_defineProperty(this, "apiRoot", void 0);
_defineProperty(this, "branch", void 0);
_defineProperty(this, "repo", void 0);
_defineProperty(this, "requestFunction", void 0);
_defineProperty(this, "repoURL", void 0);
_defineProperty(this, "commitAuthor", void 0);
_defineProperty(this, "mergeStrategy", void 0);
_defineProperty(this, "initialWorkflowStatus", void 0);
_defineProperty(this, "cmsLabelPrefix", void 0);
_defineProperty(this, "buildRequest", req => {
const withRoot = _decapCmsLibUtil.unsentRequest.withRoot(this.apiRoot)(req);
if (withRoot.has('cache')) {
return withRoot;
} else {
const withNoCache = _decapCmsLibUtil.unsentRequest.withNoCache(withRoot);
return withNoCache;
}
});
_defineProperty(this, "request", req => {
try {
return (0, _decapCmsLibUtil.requestWithBackoff)(this, req);
} catch (err) {
throw new _decapCmsLibUtil.APIError(err.message, null, API_NAME);
}
});
_defineProperty(this, "responseToJSON", (0, _decapCmsLibUtil.responseParser)({
format: 'json',
apiName: API_NAME
}));
_defineProperty(this, "responseToBlob", (0, _decapCmsLibUtil.responseParser)({
format: 'blob',
apiName: API_NAME
}));
_defineProperty(this, "responseToText", (0, _decapCmsLibUtil.responseParser)({
format: 'text',
apiName: API_NAME
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
_defineProperty(this, "requestJSON", req => this.request(req).then(this.responseToJSON));
_defineProperty(this, "requestText", req => this.request(req).then(this.responseToText));
_defineProperty(this, "user", () => this.requestJSON('/user'));
_defineProperty(this, "hasWriteAccess", async () => {
const response = await this.request(this.repoURL);
if (response.status === 404) {
throw Error('Repo not found');
}
return response.ok;
});
_defineProperty(this, "getBranch", async branchName => {
const branch = await this.requestJSON(`${this.repoURL}/refs/branches/${branchName}`);
return branch;
});
_defineProperty(this, "branchCommitSha", async branch => {
const {
target: {
hash: branchSha
}
} = await this.getBranch(branch);
return branchSha;
});
_defineProperty(this, "defaultBranchCommitSha", () => {
return this.branchCommitSha(this.branch);
});
_defineProperty(this, "isFile", ({
type
}) => type === 'commit_file');
_defineProperty(this, "getFileId", (commitHash, path) => {
return `${commitHash}/${path}`;
});
_defineProperty(this, "processFile", file => _objectSpread({
id: file.id,
type: file.type,
path: file.path,
name: (0, _decapCmsLibUtil.basename)(file.path)
}, file.commit && file.commit.hash ? {
id: this.getFileId(file.commit.hash, file.path)
} : {}));
_defineProperty(this, "processFiles", files => files.filter(this.isFile).map(this.processFile));
_defineProperty(this, "readFile", async (path, sha, {
parseText = true,
branch = this.branch,
head = ''
} = {}) => {
const fetchContent = async () => {
const node = head ? head : await this.branchCommitSha(branch);
const content = await this.request({
url: `${this.repoURL}/src/${node}/${path}`,
cache: 'no-store'
}).then(parseText ? this.responseToText : this.responseToBlob);
return content;
};
const content = await (0, _decapCmsLibUtil.readFile)(sha, fetchContent, _decapCmsLibUtil.localForage, parseText);
return content;
});
_defineProperty(this, "getEntriesAndCursor", jsonResponse => {
const {
size: count,
page,
pagelen: pageSize,
next,
previous: prev,
values: entries
} = jsonResponse;
const pageCount = pageSize && count ? Math.ceil(count / pageSize) : undefined;
return {
entries,
cursor: _decapCmsLibUtil.Cursor.create({
actions: [...(next ? ['next'] : []), ...(prev ? ['prev'] : [])],
meta: {
page,
count,
pageSize,
pageCount
},
data: {
links: {
next,
prev
}
}
})
};
});
_defineProperty(this, "listFiles", async (path, depth = 1, pagelen, branch) => {
const node = await this.branchCommitSha(branch);
const result = await this.requestJSON({
url: `${this.repoURL}/src/${node}/${path}`,
params: {
max_depth: depth,
pagelen
}
}).catch(replace404WithEmptyResponse);
const {
entries,
cursor
} = this.getEntriesAndCursor(result);
return {
entries: this.processFiles(entries),
cursor: cursor
};
});
_defineProperty(this, "traverseCursor", async (cursor, action) => (0, _flow2.default)([this.requestJSON, (0, _decapCmsLibUtil.then)(this.getEntriesAndCursor), (0, _decapCmsLibUtil.then)(({
cursor: newCursor,
entries
}) => ({
cursor: newCursor,
entries: this.processFiles(entries)
}))])(cursor.data.getIn(['links', action])));
_defineProperty(this, "listAllFiles", async (path, depth, branch) => {
const {
cursor: initialCursor,
entries: initialEntries
} = await this.listFiles(path, depth, 100, branch);
const entries = [...initialEntries];
let currentCursor = initialCursor;
while (currentCursor && currentCursor.actions.has('next')) {
const {
cursor: newCursor,
entries: newEntries
} = await this.traverseCursor(currentCursor, 'next');
entries.push(...newEntries);
currentCursor = newCursor;
}
return this.processFiles(entries);
});
_defineProperty(this, "deleteFiles", (paths, message) => {
const body = new FormData();
paths.forEach(path => {
body.append('files', path);
});
body.append('branch', this.branch);
if (message) {
body.append('message', message);
}
if (this.commitAuthor) {
const {
name,
email
} = this.commitAuthor;
body.append('author', `${name} <${email}>`);
}
return (0, _flow2.default)([_decapCmsLibUtil.unsentRequest.withMethod('POST'), _decapCmsLibUtil.unsentRequest.withBody(body), this.request])(`${this.repoURL}/src`);
});
this.apiRoot = config.apiRoot || 'https://api.bitbucket.org/2.0';
this.branch = config.branch || 'master';
this.repo = config.repo || '';
this.requestFunction = config.requestFunction || _decapCmsLibUtil.unsentRequest.performRequest;
// Allow overriding this.hasWriteAccess
this.hasWriteAccess = config.hasWriteAccess || this.hasWriteAccess;
this.repoURL = this.repo ? `/repositories/${this.repo}` : '';
this.mergeStrategy = config.squashMerges ? 'squash' : 'merge_commit';
this.initialWorkflowStatus = config.initialWorkflowStatus;
this.cmsLabelPrefix = config.cmsLabelPrefix;
}
async readFileMetadata(path, sha) {
const fetchFileMetadata = async () => {
try {
const {
values
} = await this.requestJSON({
url: `${this.repoURL}/commits`,
params: {
path,
include: this.branch
}
});
const commit = values[0];
return {
author: commit.author.user ? commit.author.user.display_name || commit.author.user.nickname : commit.author.raw,
updatedOn: commit.date
};
} catch (e) {
return {
author: '',
updatedOn: ''
};
}
};
const fileMetadata = await (0, _decapCmsLibUtil.readFileMetadata)(sha, fetchFileMetadata, _decapCmsLibUtil.localForage);
return fileMetadata;
}
async isShaExistsInBranch(branch, sha) {
const {
values
} = await this.requestJSON({
url: `${this.repoURL}/commits`,
params: {
include: branch,
pagelen: 100
}
}).catch(e => {
console.log(`Failed getting commits for branch '${branch}'`, e);
return [];
});
return values.some(v => v.hash === sha);
}
async uploadFiles(files, {
commitMessage,
branch,
parentSha
}) {
const formData = new FormData();
const toMove = [];
files.forEach(file => {
if (file.delete) {
// delete the file
formData.append('files', file.path);
} else if (file.newPath) {
const contentBlob = (0, _get2.default)(file, 'fileObj', new Blob([file.raw]));
toMove.push({
from: file.path,
to: file.newPath,
contentBlob
});
} else {
// add/modify the file
const contentBlob = (0, _get2.default)(file, 'fileObj', new Blob([file.raw]));
// Third param is filename header, in case path is `message`, `branch`, etc.
formData.append(file.path, contentBlob, (0, _decapCmsLibUtil.basename)(file.path));
}
});
for (const {
from,
to,
contentBlob
} of toMove) {
const sourceDir = (0, _path.dirname)(from);
const destDir = (0, _path.dirname)(to);
const filesBranch = parentSha ? this.branch : branch;
const files = await this.listAllFiles(sourceDir, 100, filesBranch);
for (const file of files) {
// to move a file in Bitbucket we need to delete the old path
// and upload the file content to the new path
// NOTE: this is very wasteful, and also the Bitbucket `diff` API
// reports these files as deleted+added instead of renamed
// delete current path
formData.append('files', file.path);
// create in new path
const content = file.path === from ? contentBlob : await this.readFile(file.path, null, {
branch: filesBranch,
parseText: false
});
formData.append(file.path.replace(sourceDir, destDir), content, (0, _decapCmsLibUtil.basename)(file.path));
}
}
if (commitMessage) {
formData.append('message', commitMessage);
}
if (this.commitAuthor) {
const {
name,
email
} = this.commitAuthor;
formData.append('author', `${name} <${email}>`);
}
formData.append('branch', branch);
if (parentSha) {
formData.append('parents', parentSha);
}
try {
await this.requestText({
url: `${this.repoURL}/src`,
method: 'POST',
body: formData
});
} catch (error) {
const message = error.message || '';
// very descriptive message from Bitbucket
if (parentSha && message.includes('Something went wrong')) {
await (0, _decapCmsLibUtil.throwOnConflictingBranches)(branch, name => this.getBranch(name), API_NAME);
}
throw error;
}
return files;
}
async persistFiles(dataFiles, mediaFiles, options) {
const files = [...dataFiles, ...mediaFiles];
if (options.useWorkflow) {
const slug = dataFiles[0].slug;
return this.editorialWorkflowGit(files, slug, options);
} else {
return this.uploadFiles(files, {
commitMessage: options.commitMessage,
branch: this.branch
});
}
}
async addPullRequestComment(pullRequest, comment) {
await this.requestJSON({
method: 'POST',
url: `${this.repoURL}/pullrequests/${pullRequest.id}/comments`,
headers: {
'Content-Type': APPLICATION_JSON
},
body: JSON.stringify({
content: {
raw: comment
}
})
});
}
async getPullRequestLabel(id) {
const comments = await this.requestJSON({
url: `${this.repoURL}/pullrequests/${id}/comments`,
params: {
pagelen: 100
}
});
return comments.values.map(c => c.content.raw)[comments.values.length - 1];
}
async createPullRequest(branch, commitMessage, status) {
const pullRequest = await this.requestJSON({
method: 'POST',
url: `${this.repoURL}/pullrequests`,
headers: {
'Content-Type': APPLICATION_JSON
},
body: JSON.stringify({
title: commitMessage,
source: {
branch: {
name: branch
}
},
destination: {
branch: {
name: this.branch
}
},
description: _decapCmsLibUtil.DEFAULT_PR_BODY,
close_source_branch: true
})
});
// use comments for status labels
await this.addPullRequestComment(pullRequest, (0, _decapCmsLibUtil.statusToLabel)(status, this.cmsLabelPrefix));
}
async getDifferences(source, destination = this.branch) {
if (source === destination) {
return [];
}
const rawDiff = await this.requestText({
url: `${this.repoURL}/diff/${source}..${destination}`,
params: {
binary: false
}
});
const diffs = (0, _whatTheDiff.parse)(rawDiff).map(d => {
var _d$oldPath, _d$newPath;
const oldPath = ((_d$oldPath = d.oldPath) === null || _d$oldPath === void 0 ? void 0 : _d$oldPath.replace(/b\//, '')) || '';
const newPath = ((_d$newPath = d.newPath) === null || _d$newPath === void 0 ? void 0 : _d$newPath.replace(/b\//, '')) || '';
const path = newPath || oldPath;
return {
oldPath,
newPath,
status: d.status,
newFile: d.status === 'added',
path,
binary: d.binary || /.svg$/.test(path)
};
});
return diffs;
}
async editorialWorkflowGit(files, slug, options) {
const contentKey = (0, _decapCmsLibUtil.generateContentKey)(options.collectionName, slug);
const branch = (0, _decapCmsLibUtil.branchFromContentKey)(contentKey);
const unpublished = options.unpublished || false;
if (!unpublished) {
const defaultBranchSha = await this.branchCommitSha(this.branch);
await this.uploadFiles(files, {
commitMessage: options.commitMessage,
branch,
parentSha: defaultBranchSha
});
await this.createPullRequest(branch, options.commitMessage, options.status || this.initialWorkflowStatus);
} else {
// mark files for deletion
const diffs = await this.getDifferences(branch);
const toDelete = [];
for (const diff of diffs.filter(d => d.binary && d.status !== 'deleted')) {
if (!files.some(file => file.path === diff.path)) {
toDelete.push({
path: diff.path,
delete: true
});
}
}
await this.uploadFiles([...files, ...toDelete], {
commitMessage: options.commitMessage,
branch
});
}
}
async getPullRequests(sourceBranch) {
const sourceQuery = sourceBranch ? `source.branch.name = "${sourceBranch}"` : `source.branch.name ~ "${_decapCmsLibUtil.CMS_BRANCH_PREFIX}/"`;
const pullRequests = await this.requestJSON({
url: `${this.repoURL}/pullrequests`,
params: {
pagelen: 50,
q: (0, _commonTags.oneLine)`
source.repository.full_name = "${this.repo}"
AND state = "${BitBucketPullRequestState.OPEN}"
AND destination.branch.name = "${this.branch}"
AND comment_count > 0
AND ${sourceQuery}
`
}
});
const labels = await Promise.all(pullRequests.values.map(pr => this.getPullRequestLabel(pr.id)));
return pullRequests.values.filter((_, index) => (0, _decapCmsLibUtil.isCMSLabel)(labels[index], this.cmsLabelPrefix));
}
async getBranchPullRequest(branch) {
const pullRequests = await this.getPullRequests(branch);
if (pullRequests.length <= 0) {
throw new _decapCmsLibUtil.EditorialWorkflowError('content is not under editorial workflow', true);
}
return pullRequests[0];
}
async listUnpublishedBranches() {
console.log('%c Checking for Unpublished entries', 'line-height: 30px;text-align: center;font-weight: bold');
const pullRequests = await this.getPullRequests();
const branches = pullRequests.map(mr => mr.source.branch.name);
return branches;
}
async retrieveUnpublishedEntryData(contentKey) {
const {
collection,
slug
} = (0, _decapCmsLibUtil.parseContentKey)(contentKey);
const branch = (0, _decapCmsLibUtil.branchFromContentKey)(contentKey);
const pullRequest = await this.getBranchPullRequest(branch);
const diffs = await this.getDifferences(branch);
const label = await this.getPullRequestLabel(pullRequest.id);
const status = (0, _decapCmsLibUtil.labelToStatus)(label, this.cmsLabelPrefix);
const updatedAt = pullRequest.updated_on;
const pullRequestAuthor = pullRequest.author.display_name;
return {
collection,
slug,
status,
// TODO: get real id
diffs: diffs.filter(d => d.status !== 'deleted').map(d => ({
path: d.path,
newFile: d.newFile,
id: ''
})),
updatedAt,
pullRequestAuthor
};
}
async updateUnpublishedEntryStatus(collection, slug, newStatus) {
const contentKey = (0, _decapCmsLibUtil.generateContentKey)(collection, slug);
const branch = (0, _decapCmsLibUtil.branchFromContentKey)(contentKey);
const pullRequest = await this.getBranchPullRequest(branch);
await this.addPullRequestComment(pullRequest, (0, _decapCmsLibUtil.statusToLabel)(newStatus, this.cmsLabelPrefix));
}
async mergePullRequest(pullRequest) {
await this.requestJSON({
method: 'POST',
url: `${this.repoURL}/pullrequests/${pullRequest.id}/merge`,
headers: {
'Content-Type': APPLICATION_JSON
},
body: JSON.stringify({
message: _decapCmsLibUtil.MERGE_COMMIT_MESSAGE,
close_source_branch: true,
merge_strategy: this.mergeStrategy
})
});
}
async publishUnpublishedEntry(collectionName, slug) {
const contentKey = (0, _decapCmsLibUtil.generateContentKey)(collectionName, slug);
const branch = (0, _decapCmsLibUtil.branchFromContentKey)(contentKey);
const pullRequest = await this.getBranchPullRequest(branch);
await this.mergePullRequest(pullRequest);
}
async declinePullRequest(pullRequest) {
await this.requestJSON({
method: 'POST',
url: `${this.repoURL}/pullrequests/${pullRequest.id}/decline`
});
}
async deleteBranch(branch) {
await this.request({
method: 'DELETE',
url: `${this.repoURL}/refs/branches/${branch}`
});
}
async deleteUnpublishedEntry(collectionName, slug) {
const contentKey = (0, _decapCmsLibUtil.generateContentKey)(collectionName, slug);
const branch = (0, _decapCmsLibUtil.branchFromContentKey)(contentKey);
const pullRequest = await this.getBranchPullRequest(branch);
await this.declinePullRequest(pullRequest);
await this.deleteBranch(branch);
}
async getPullRequestStatuses(pullRequest) {
const statuses = await this.requestJSON({
url: `${this.repoURL}/pullrequests/${pullRequest.id}/statuses`,
params: {
pagelen: 100
}
});
return statuses.values;
}
async getStatuses(collectionName, slug) {
const contentKey = (0, _decapCmsLibUtil.generateContentKey)(collectionName, slug);
const branch = (0, _decapCmsLibUtil.branchFromContentKey)(contentKey);
const pullRequest = await this.getBranchPullRequest(branch);
const statuses = await this.getPullRequestStatuses(pullRequest);
return statuses.map(({
key,
state,
url
}) => ({
context: key,
state: state === BitBucketPullRequestStatusState.Successful ? _decapCmsLibUtil.PreviewState.Success : _decapCmsLibUtil.PreviewState.Other,
target_url: url
}));
}
async getUnpublishedEntrySha(collection, slug) {
const contentKey = (0, _decapCmsLibUtil.generateContentKey)(collection, slug);
const branch = (0, _decapCmsLibUtil.branchFromContentKey)(contentKey);
const pullRequest = await this.getBranchPullRequest(branch);
return pullRequest.destination.commit.hash;
}
}
exports.default = API;

View File

@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _base = _interopRequireDefault(require("@emotion/styled/base"));
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _decapCmsLibAuth = require("decap-cms-lib-auth");
var _decapCmsUiDefault = require("decap-cms-ui-default");
var _react2 = require("@emotion/react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _EMOTION_STRINGIFIED_CSS_ERROR__() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
const LoginButtonIcon = /*#__PURE__*/(0, _base.default)(_decapCmsUiDefault.Icon, {
target: "e15sc0jo0",
label: "LoginButtonIcon"
})(process.env.NODE_ENV === "production" ? {
name: "1gnqu05",
styles: "margin-right:18px"
} : {
name: "1gnqu05",
styles: "margin-right:18px",
map: "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9BdXRoZW50aWNhdGlvblBhZ2UuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBTW9DIiwiZmlsZSI6Ii4uLy4uL3NyYy9BdXRoZW50aWNhdGlvblBhZ2UuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgUmVhY3QgZnJvbSAncmVhY3QnO1xuaW1wb3J0IFByb3BUeXBlcyBmcm9tICdwcm9wLXR5cGVzJztcbmltcG9ydCBzdHlsZWQgZnJvbSAnQGVtb3Rpb24vc3R5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+XG4gICAgICAgICAgICA8TG9naW5CdXR0b25JY29uIHR5cGU9XCJiaXRidWNrZXRcIiAvPlxuICAgICAgICAgICAge2luUHJvZ3Jlc3MgPyB0KCdhdXRoLmxvZ2dpbmdJbicpIDogdCgnYXV0aC5sb2dpbldpdGhCaXRidWNrZXQnKX1cbiAgICAgICAgICA8L1JlYWN0LkZyYWdtZW50PlxuICAgICAgICApfVxuICAgICAgICB0PXt0fVxuICAgICAgLz5cbiAgICApO1xuICB9XG59XG4iXX0= */",
toString: _EMOTION_STRINGIFIED_CSS_ERROR__
});
class BitbucketAuthenticationPage extends _react.default.Component {
constructor(...args) {
super(...args);
_defineProperty(this, "state", {});
_defineProperty(this, "handleLogin", e => {
e.preventDefault();
this.auth.authenticate(this.authSettings, (err, data) => {
if (err) {
this.setState({
loginError: err.toString()
});
return;
}
this.props.onLogin(data);
});
});
}
componentDidMount() {
const {
auth_type: authType = ''
} = this.props.config.backend;
if (authType === 'implicit') {
const {
base_url = 'https://bitbucket.org',
auth_endpoint = 'site/oauth2/authorize',
app_id = ''
} = this.props.config.backend;
this.auth = new _decapCmsLibAuth.ImplicitAuthenticator({
base_url,
auth_endpoint,
app_id,
clearHash: this.props.clearHash
});
// Complete implicit authentication if we were redirected back to from the provider.
this.auth.completeAuth((err, data) => {
if (err) {
this.setState({
loginError: err.toString()
});
return;
}
this.props.onLogin(data);
});
this.authSettings = {
scope: 'repository:write'
};
} else {
this.auth = new _decapCmsLibAuth.NetlifyAuthenticator({
base_url: this.props.base_url,
site_id: document.location.host.split(':')[0] === 'localhost' ? 'demo.decapcms.org' : this.props.siteId,
auth_endpoint: this.props.authEndpoint
});
this.authSettings = {
provider: 'bitbucket',
scope: 'repo'
};
}
}
render() {
const {
inProgress,
config,
t
} = this.props;
return (0, _react2.jsx)(_decapCmsUiDefault.AuthenticationPage, {
onLogin: this.handleLogin,
loginDisabled: inProgress,
loginErrorMessage: this.state.loginError,
logoUrl: config.logo_url,
siteUrl: config.site_url,
renderButtonContent: () => (0, _react2.jsx)(_react.default.Fragment, null, (0, _react2.jsx)(LoginButtonIcon, {
type: "bitbucket"
}), inProgress ? t('auth.loggingIn') : t('auth.loginWithBitbucket')),
t: t
});
}
}
exports.default = BitbucketAuthenticationPage;
_defineProperty(BitbucketAuthenticationPage, "propTypes", {
onLogin: _propTypes.default.func.isRequired,
inProgress: _propTypes.default.bool,
base_url: _propTypes.default.string,
siteId: _propTypes.default.string,
authEndpoint: _propTypes.default.string,
config: _propTypes.default.object.isRequired,
clearHash: _propTypes.default.func,
t: _propTypes.default.func.isRequired
});

View File

@@ -0,0 +1,90 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GitLfsClient = void 0;
var _minimatch = _interopRequireDefault(require("minimatch"));
var _decapCmsLibUtil = require("decap-cms-lib-util");
const _excluded = ["sha"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
class GitLfsClient {
constructor(enabled, rootURL, patterns, makeAuthorizedRequest) {
this.enabled = enabled;
this.rootURL = rootURL;
this.patterns = patterns;
this.makeAuthorizedRequest = makeAuthorizedRequest;
}
matchPath(path) {
return this.patterns.some(pattern => (0, _minimatch.default)(path, pattern, {
matchBase: true
}));
}
async uploadResource(pointer, resource) {
const requests = await this.getResourceUploadRequests([pointer]);
for (const request of requests) {
await this.doUpload(request.actions.upload, resource);
if (request.actions.verify) {
await this.doVerify(request.actions.verify, request);
}
}
return pointer.sha;
}
async doUpload(upload, resource) {
await _decapCmsLibUtil.unsentRequest.fetchWithTimeout(decodeURI(upload.href), {
method: 'PUT',
body: resource,
headers: upload.header
});
}
async doVerify(verify, object) {
this.makeAuthorizedRequest({
url: decodeURI(verify.href),
method: 'POST',
headers: _objectSpread(_objectSpread({}, GitLfsClient.defaultContentHeaders), verify.header),
body: JSON.stringify({
oid: object.oid,
size: object.size
})
});
}
async getResourceUploadRequests(objects) {
const response = await this.makeAuthorizedRequest({
url: `${this.rootURL}/objects/batch`,
method: 'POST',
headers: GitLfsClient.defaultContentHeaders,
body: JSON.stringify({
operation: 'upload',
transfers: ['basic'],
objects: objects.map(_ref => {
let {
sha
} = _ref,
rest = _objectWithoutProperties(_ref, _excluded);
return _objectSpread(_objectSpread({}, rest), {}, {
oid: sha
});
})
})
});
return (await response.json()).objects.filter(object => {
if ('error' in object) {
console.error(object.error);
return false;
}
return object.actions;
});
}
}
exports.GitLfsClient = GitLfsClient;
_defineProperty(GitLfsClient, "defaultContentHeaders", {
Accept: 'application/vnd.git-lfs+json',
['Content-Type']: 'application/vnd.git-lfs+json'
});

View File

@@ -0,0 +1,542 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _trimStart2 = _interopRequireDefault(require("lodash/trimStart"));
var _semaphore = _interopRequireDefault(require("semaphore"));
var _commonTags = require("common-tags");
var _decapCmsLibUtil = require("decap-cms-lib-util");
var _decapCmsLibAuth = require("decap-cms-lib-auth");
var _AuthenticationPage = _interopRequireDefault(require("./AuthenticationPage"));
var _API = _interopRequireWildcard(require("./API"));
var _gitLfsClient = require("./git-lfs-client");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
const MAX_CONCURRENT_DOWNLOADS = 10;
const STATUS_PAGE = 'https://bitbucket.status.atlassian.com';
const BITBUCKET_STATUS_ENDPOINT = `${STATUS_PAGE}/api/v2/components.json`;
const BITBUCKET_OPERATIONAL_UNITS = ['API', 'Authentication and user management', 'Git LFS'];
const {
fetchWithTimeout: fetch
} = _decapCmsLibUtil.unsentRequest;
// Implementation wrapper class
class BitbucketBackend {
constructor(config, options = {}) {
_defineProperty(this, "lock", void 0);
_defineProperty(this, "api", void 0);
_defineProperty(this, "updateUserCredentials", void 0);
_defineProperty(this, "options", void 0);
_defineProperty(this, "repo", void 0);
_defineProperty(this, "isBranchConfigured", void 0);
_defineProperty(this, "branch", void 0);
_defineProperty(this, "apiRoot", void 0);
_defineProperty(this, "baseUrl", void 0);
_defineProperty(this, "siteId", void 0);
_defineProperty(this, "token", void 0);
_defineProperty(this, "mediaFolder", void 0);
_defineProperty(this, "refreshToken", void 0);
_defineProperty(this, "refreshedTokenPromise", void 0);
_defineProperty(this, "authenticator", void 0);
_defineProperty(this, "_mediaDisplayURLSem", void 0);
_defineProperty(this, "squashMerges", void 0);
_defineProperty(this, "cmsLabelPrefix", void 0);
_defineProperty(this, "previewContext", void 0);
_defineProperty(this, "largeMediaURL", void 0);
_defineProperty(this, "_largeMediaClientPromise", void 0);
_defineProperty(this, "authType", void 0);
_defineProperty(this, "requestFunction", async req => {
const token = await this.getToken();
const authorizedRequest = _decapCmsLibUtil.unsentRequest.withHeaders({
Authorization: `Bearer ${token}`
}, req);
return _decapCmsLibUtil.unsentRequest.performRequest(authorizedRequest);
});
_defineProperty(this, "apiRequestFunction", async req => {
const token = this.refreshedTokenPromise ? await this.refreshedTokenPromise : this.token;
const authorizedRequest = _decapCmsLibUtil.unsentRequest.withHeaders({
Authorization: `Bearer ${token}`
}, req);
const response = await _decapCmsLibUtil.unsentRequest.performRequest(authorizedRequest);
if (response.status === 401) {
const json = await response.json().catch(() => null);
if (json && json.type === 'error' && /^access token expired/i.test(json.error.message)) {
const newToken = await this.getRefreshedAccessToken();
const reqWithNewToken = _decapCmsLibUtil.unsentRequest.withHeaders({
Authorization: `Bearer ${newToken}`
}, req);
return _decapCmsLibUtil.unsentRequest.performRequest(reqWithNewToken);
}
}
return response;
});
this.options = _objectSpread({
proxied: false,
API: null,
updateUserCredentials: async () => null,
initialWorkflowStatus: ''
}, options);
if (!this.options.proxied && (config.backend.repo === null || config.backend.repo === undefined)) {
throw new Error('The BitBucket backend needs a "repo" in the backend configuration.');
}
this.api = this.options.API || null;
this.updateUserCredentials = this.options.updateUserCredentials;
this.repo = config.backend.repo || '';
this.branch = config.backend.branch || 'master';
this.isBranchConfigured = config.backend.branch ? true : false;
this.apiRoot = config.backend.api_root || 'https://api.bitbucket.org/2.0';
this.baseUrl = config.base_url || '';
this.siteId = config.site_id || '';
this.largeMediaURL = config.backend.large_media_url || `https://bitbucket.org/${config.backend.repo}/info/lfs`;
this.token = '';
this.mediaFolder = config.media_folder;
this.squashMerges = config.backend.squash_merges || false;
this.cmsLabelPrefix = config.backend.cms_label_prefix || '';
this.previewContext = config.backend.preview_context || '';
this.lock = (0, _decapCmsLibUtil.asyncLock)();
this.authType = config.backend.auth_type || '';
}
isGitBackend() {
return true;
}
async status() {
const api = await fetch(BITBUCKET_STATUS_ENDPOINT).then(res => res.json()).then(res => {
return res['components'].filter(statusComponent => BITBUCKET_OPERATIONAL_UNITS.includes(statusComponent.name)).every(statusComponent => statusComponent.status === 'operational');
}).catch(e => {
console.warn('Failed getting BitBucket status', e);
return true;
});
let auth = false;
// no need to check auth if api is down
if (api) {
var _this$api;
auth = (await ((_this$api = this.api) === null || _this$api === void 0 ? void 0 : _this$api.user().then(user => !!user).catch(e => {
console.warn('Failed getting Bitbucket user', e);
return false;
}))) || false;
}
return {
auth: {
status: auth
},
api: {
status: api,
statusPage: STATUS_PAGE
}
};
}
authComponent() {
return _AuthenticationPage.default;
}
setUser(user) {
this.token = user.token;
this.api = new _API.default({
requestFunction: this.apiRequestFunction,
branch: this.branch,
repo: this.repo,
squashMerges: this.squashMerges,
cmsLabelPrefix: this.cmsLabelPrefix,
initialWorkflowStatus: this.options.initialWorkflowStatus
});
}
restoreUser(user) {
return this.authenticate(user);
}
async authenticate(state) {
this.token = state.token;
if (!this.isBranchConfigured) {
const repo = await fetch(`${this.apiRoot}/repositories/${this.repo}`, {
headers: {
Authorization: `token ${this.token}`
}
}).then(res => res.json()).catch(() => null);
if (repo) {
this.branch = repo.mainbranch.name;
}
}
this.refreshToken = state.refresh_token;
this.api = new _API.default({
requestFunction: this.apiRequestFunction,
branch: this.branch,
repo: this.repo,
apiRoot: this.apiRoot,
squashMerges: this.squashMerges,
cmsLabelPrefix: this.cmsLabelPrefix,
initialWorkflowStatus: this.options.initialWorkflowStatus
});
const isCollab = await this.api.hasWriteAccess().catch(error => {
error.message = (0, _commonTags.stripIndent)`
Repo "${this.repo}" not found.
Please ensure the repo information is spelled correctly.
If the repo is private, make sure you're logged into a Bitbucket account with access.
`;
throw error;
});
// Unauthorized user
if (!isCollab) {
throw new Error('Your BitBucket user account does not have access to this repo.');
}
// if (!this.isBranchConfigured) {
// const defaultBranchName = await getDefaultBranchName({
// backend: 'bitbucket',
// repo: this.repo,
// token: this.token,
// });
// if (defaultBranchName) {
// this.branch = defaultBranchName;
// }
// }
const user = await this.api.user();
// Authorized user
return _objectSpread(_objectSpread({}, user), {}, {
name: user.display_name,
login: user.username,
token: state.token,
avatar_url: user.links.avatar.href,
refresh_token: state.refresh_token
});
}
getRefreshedAccessToken() {
if (this.authType === 'implicit') {
throw new _decapCmsLibUtil.AccessTokenError(`Can't refresh access token when using implicit auth`);
}
if (this.refreshedTokenPromise) {
return this.refreshedTokenPromise;
}
// instantiating a new Authenticator on each refresh isn't ideal,
if (!this.authenticator) {
const cfg = {
base_url: this.baseUrl,
site_id: this.siteId
};
this.authenticator = new _decapCmsLibAuth.NetlifyAuthenticator(cfg);
}
this.refreshedTokenPromise = this.authenticator.refresh({
provider: 'bitbucket',
refresh_token: this.refreshToken
}).then(({
token,
refresh_token
}) => {
this.token = token;
this.refreshToken = refresh_token;
this.refreshedTokenPromise = undefined;
this.updateUserCredentials({
token,
refresh_token
});
return token;
});
return this.refreshedTokenPromise;
}
logout() {
this.token = null;
return;
}
getToken() {
if (this.refreshedTokenPromise) {
return this.refreshedTokenPromise;
}
return Promise.resolve(this.token);
}
async entriesByFolder(folder, extension, depth) {
let cursor;
const listFiles = () => this.api.listFiles(folder, depth, 20, this.branch).then(({
entries,
cursor: c
}) => {
cursor = c.mergeMeta({
extension
});
return entries.filter(e => (0, _decapCmsLibUtil.filterByExtension)(e, extension));
});
const head = await this.api.defaultBranchCommitSha();
const readFile = (path, id) => {
return this.api.readFile(path, id, {
head
});
};
const files = await (0, _decapCmsLibUtil.entriesByFolder)(listFiles, readFile, this.api.readFileMetadata.bind(this.api), _API.API_NAME);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
files[_decapCmsLibUtil.CURSOR_COMPATIBILITY_SYMBOL] = cursor;
return files;
}
async listAllFiles(folder, extension, depth) {
const files = await this.api.listAllFiles(folder, depth, this.branch);
const filtered = files.filter(file => (0, _decapCmsLibUtil.filterByExtension)(file, extension));
return filtered;
}
async allEntriesByFolder(folder, extension, depth) {
const head = await this.api.defaultBranchCommitSha();
const readFile = (path, id) => {
return this.api.readFile(path, id, {
head
});
};
const files = await (0, _decapCmsLibUtil.allEntriesByFolder)({
listAllFiles: () => this.listAllFiles(folder, extension, depth),
readFile,
readFileMetadata: this.api.readFileMetadata.bind(this.api),
apiName: _API.API_NAME,
branch: this.branch,
localForage: _decapCmsLibUtil.localForage,
folder,
extension,
depth,
getDefaultBranch: () => Promise.resolve({
name: this.branch,
sha: head
}),
isShaExistsInBranch: this.api.isShaExistsInBranch.bind(this.api),
getDifferences: (source, destination) => this.api.getDifferences(source, destination),
getFileId: path => Promise.resolve(this.api.getFileId(head, path)),
filterFile: file => (0, _decapCmsLibUtil.filterByExtension)(file, extension)
});
return files;
}
async entriesByFiles(files) {
const head = await this.api.defaultBranchCommitSha();
const readFile = (path, id) => {
return this.api.readFile(path, id, {
head
});
};
return (0, _decapCmsLibUtil.entriesByFiles)(files, readFile, this.api.readFileMetadata.bind(this.api), _API.API_NAME);
}
getEntry(path) {
return this.api.readFile(path).then(data => ({
file: {
path,
id: null
},
data: data
}));
}
getMedia(mediaFolder = this.mediaFolder) {
return this.api.listAllFiles(mediaFolder, 1, this.branch).then(files => files.map(({
id,
name,
path
}) => ({
id,
name,
path,
displayURL: {
id,
path
}
})));
}
getLargeMediaClient() {
if (!this._largeMediaClientPromise) {
this._largeMediaClientPromise = (async () => {
const patterns = await this.api.readFile('.gitattributes').then(attributes => (0, _decapCmsLibUtil.getLargeMediaPatternsFromGitAttributesFile)(attributes)).catch(err => {
if (err.status === 404) {
console.log('This 404 was expected and handled appropriately.');
} else {
console.error(err);
}
return [];
});
return new _gitLfsClient.GitLfsClient(!!(this.largeMediaURL && patterns.length > 0), this.largeMediaURL, patterns, this.requestFunction);
})();
}
return this._largeMediaClientPromise;
}
getMediaDisplayURL(displayURL) {
this._mediaDisplayURLSem = this._mediaDisplayURLSem || (0, _semaphore.default)(MAX_CONCURRENT_DOWNLOADS);
return (0, _decapCmsLibUtil.getMediaDisplayURL)(displayURL, this.api.readFile.bind(this.api), this._mediaDisplayURLSem);
}
async getMediaFile(path) {
const name = (0, _decapCmsLibUtil.basename)(path);
const blob = await (0, _decapCmsLibUtil.getMediaAsBlob)(path, null, this.api.readFile.bind(this.api));
const fileObj = (0, _decapCmsLibUtil.blobToFileObj)(name, blob);
const url = URL.createObjectURL(fileObj);
const id = await (0, _decapCmsLibUtil.getBlobSHA)(fileObj);
return {
id,
displayURL: url,
path,
name,
size: fileObj.size,
file: fileObj,
url
};
}
async persistEntry(entry, options) {
const client = await this.getLargeMediaClient();
// persistEntry is a transactional operation
return (0, _decapCmsLibUtil.runWithLock)(this.lock, async () => this.api.persistFiles(entry.dataFiles, client.enabled ? await (0, _decapCmsLibUtil.getLargeMediaFilteredMediaFiles)(client, entry.assets) : entry.assets, options), 'Failed to acquire persist entry lock');
}
async persistMedia(mediaFile, options) {
const {
fileObj,
path
} = mediaFile;
const displayURL = fileObj ? URL.createObjectURL(fileObj) : '';
const client = await this.getLargeMediaClient();
const fixedPath = path.startsWith('/') ? path.slice(1) : path;
if (!client.enabled || !client.matchPath(fixedPath)) {
return this._persistMedia(mediaFile, options);
}
const persistMediaArgument = await (0, _decapCmsLibUtil.getPointerFileForMediaFileObj)(client, fileObj, path);
return _objectSpread(_objectSpread({}, await this._persistMedia(persistMediaArgument, options)), {}, {
displayURL
});
}
async _persistMedia(mediaFile, options) {
const fileObj = mediaFile.fileObj;
const [id] = await Promise.all([(0, _decapCmsLibUtil.getBlobSHA)(fileObj), this.api.persistFiles([], [mediaFile], options)]);
const url = URL.createObjectURL(fileObj);
return {
displayURL: url,
path: (0, _trimStart2.default)(mediaFile.path, '/k'),
name: fileObj.name,
size: fileObj.size,
id,
file: fileObj,
url
};
}
deleteFiles(paths, commitMessage) {
return this.api.deleteFiles(paths, commitMessage);
}
traverseCursor(cursor, action) {
return this.api.traverseCursor(cursor, action).then(async ({
entries,
cursor: newCursor
}) => {
var _cursor$meta;
const extension = (_cursor$meta = cursor.meta) === null || _cursor$meta === void 0 ? void 0 : _cursor$meta.get('extension');
if (extension) {
entries = entries.filter(e => (0, _decapCmsLibUtil.filterByExtension)(e, extension));
newCursor = newCursor.mergeMeta({
extension
});
}
const head = await this.api.defaultBranchCommitSha();
const readFile = (path, id) => {
return this.api.readFile(path, id, {
head
});
};
const entriesWithData = await (0, _decapCmsLibUtil.entriesByFiles)(entries, readFile, this.api.readFileMetadata.bind(this.api), _API.API_NAME);
return {
entries: entriesWithData,
cursor: newCursor
};
});
}
async loadMediaFile(path, id, {
branch
}) {
const readFile = async (path, id, {
parseText
}) => {
const content = await this.api.readFile(path, id, {
branch,
parseText
});
return content;
};
const blob = await (0, _decapCmsLibUtil.getMediaAsBlob)(path, id, readFile);
const name = (0, _decapCmsLibUtil.basename)(path);
const fileObj = (0, _decapCmsLibUtil.blobToFileObj)(name, blob);
return {
id: path,
displayURL: URL.createObjectURL(fileObj),
path,
name,
size: fileObj.size,
file: fileObj
};
}
async unpublishedEntries() {
const listEntriesKeys = () => this.api.listUnpublishedBranches().then(branches => branches.map(branch => (0, _decapCmsLibUtil.contentKeyFromBranch)(branch)));
const ids = await (0, _decapCmsLibUtil.unpublishedEntries)(listEntriesKeys);
return ids;
}
async unpublishedEntry({
id,
collection,
slug
}) {
if (id) {
const data = await this.api.retrieveUnpublishedEntryData(id);
return data;
} else if (collection && slug) {
const entryId = (0, _decapCmsLibUtil.generateContentKey)(collection, slug);
const data = await this.api.retrieveUnpublishedEntryData(entryId);
return data;
} else {
throw new Error('Missing unpublished entry id or collection and slug');
}
}
getBranch(collection, slug) {
const contentKey = (0, _decapCmsLibUtil.generateContentKey)(collection, slug);
const branch = (0, _decapCmsLibUtil.branchFromContentKey)(contentKey);
return branch;
}
async unpublishedEntryDataFile(collection, slug, path, id) {
const branch = this.getBranch(collection, slug);
const data = await this.api.readFile(path, id, {
branch
});
return data;
}
async unpublishedEntryMediaFile(collection, slug, path, id) {
const branch = this.getBranch(collection, slug);
const mediaFile = await this.loadMediaFile(path, id, {
branch
});
return mediaFile;
}
async updateUnpublishedEntryStatus(collection, slug, newStatus) {
// updateUnpublishedEntryStatus is a transactional operation
return (0, _decapCmsLibUtil.runWithLock)(this.lock, () => this.api.updateUnpublishedEntryStatus(collection, slug, newStatus), 'Failed to acquire update entry status lock');
}
async deleteUnpublishedEntry(collection, slug) {
// deleteUnpublishedEntry is a transactional operation
return (0, _decapCmsLibUtil.runWithLock)(this.lock, () => this.api.deleteUnpublishedEntry(collection, slug), 'Failed to acquire delete entry lock');
}
async publishUnpublishedEntry(collection, slug) {
// publishUnpublishedEntry is a transactional operation
return (0, _decapCmsLibUtil.runWithLock)(this.lock, () => this.api.publishUnpublishedEntry(collection, slug), 'Failed to acquire publish entry lock');
}
async getDeployPreview(collection, slug) {
try {
const statuses = await this.api.getStatuses(collection, slug);
const deployStatus = (0, _decapCmsLibUtil.getPreviewStatus)(statuses, this.previewContext);
if (deployStatus) {
const {
target_url: url,
state
} = deployStatus;
return {
url,
status: state
};
} else {
return null;
}
} catch (e) {
return null;
}
}
}
exports.default = BitbucketBackend;

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "API", {
enumerable: true,
get: function () {
return _API.default;
}
});
Object.defineProperty(exports, "AuthenticationPage", {
enumerable: true,
get: function () {
return _AuthenticationPage.default;
}
});
Object.defineProperty(exports, "BitbucketBackend", {
enumerable: true,
get: function () {
return _implementation.default;
}
});
exports.DecapCmsBackendBitbucket = void 0;
var _implementation = _interopRequireDefault(require("./implementation"));
var _API = _interopRequireDefault(require("./API"));
var _AuthenticationPage = _interopRequireDefault(require("./AuthenticationPage"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const DecapCmsBackendBitbucket = exports.DecapCmsBackendBitbucket = {
BitbucketBackend: _implementation.default,
API: _API.default,
AuthenticationPage: _AuthenticationPage.default
};

View File

@@ -0,0 +1 @@
"use strict";

View File

@@ -0,0 +1 @@
"use strict";