• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

evolvedbinary / prosemirror-lwdita / a803a5be-0d0b-4c39-8074-831cc8973bed

31 Oct 2024 10:21AM UTC coverage: 44.004% (-0.03%) from 44.032%
a803a5be-0d0b-4c39-8074-831cc8973bed

Pull #479

circleci

marmoure
[bugfix] do not manipulate strings  and use urijs instead
Pull Request #479: Images should point to the base url

175 of 369 branches covered (47.43%)

Branch coverage included in aggregate %.

2 of 5 new or added lines in 1 file covered. (40.0%)

1 existing line in 1 file now uncovered.

324 of 765 relevant lines covered (42.35%)

26.45 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

75.44
/packages/prosemirror-lwdita/src/github-integration/github.plugin.ts
1
/*!
2
Copyright (C) 2020 Evolved Binary
3

4
This program is free software: you can redistribute it and/or modify
5
it under the terms of the GNU Affero General Public License as
6
published by the Free Software Foundation, either version 3 of the
7
License, or (at your option) any later version.
8

9
This program is distributed in the hope that it will be useful,
10
but WITHOUT ANY WARRANTY; without even the implied warranty of
11
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
GNU Affero General Public License for more details.
13

14
You should have received a copy of the GNU Affero General Public License
15
along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
*/
17

18
import { xditaToJdita } from "@evolvedbinary/lwdita-xdita";
1✔
19
import { document as jditaToProsemirrorJson } from "../document";
1✔
20
import { showErrorPage } from "./request";
1✔
21
import { showToast } from "../toast";
1✔
22
import { Config } from "../config";
23
import { Localization } from "@evolvedbinary/prosemirror-lwdita-localization";
24
import urijs from "urijs";
1✔
25

26
/**
27
 * Fetches the raw content of a document from a GitHub repository.
28
 *
29
 * @param config - configuration
30
 * @param ghrepo - The GitHub repository in the format "owner/repo".
31
 * @param source - The path to the file within the repository.
32
 * @param branch - The branch from which to fetch the document.
33
 * @returns A promise that resolves to the raw content of the document as a string.
34
 *
35
 * @remarks
36
 * This function currently fetches the document from the 'main' branch of the repository.
37
 * should use the GitHub API to dynamically determine the default branch of the repository.
38
 */
39
export const fetchRawDocumentFromGitHub = async (config: Config, ghrepo: string, source: string, branch: string): Promise<string> => {
2✔
40
  // GitHub changes the raw api URL from `main` to `refs/heads/main` 
41
  // https://raw.githubusercontent.com/evolvedbinary/prosemirror-lwdita/main/packages/prosemirror-lwdita-demo/example-xdita/02-short-file.xml
42
  // https://raw.githubusercontent.com/evolvedbinary/prosemirror-lwdita/refs/heads/main/packages/prosemirror-lwdita-demo/example-xdita/02-short-file.xml
43
  const url = `https://raw.githubusercontent.com/${ghrepo}/refs/heads/${branch}/${source}`;
2✔
44
  const response = await fetch(url);
2✔
45

46
  if (!response.ok) {
2✔
47
    showErrorPage(config, 'fileNotFound', '', response.statusText);
1✔
48
  }
49
  //TODO: Handle errors
50
  return response.text();
1✔
51
};
52

53
/**
54
 * Transforms a raw GitHub document into a ProseMirror state save.
55
 *
56
 * @param rawDocument - The raw xdita document as a string.
57
 * @returns A promise that resolves to a record containing the ProseMirror state save.
58
 */
59
// eslint-disable-next-line @typescript-eslint/no-explicit-any
60
export const transformGitHubDocumentToProsemirrorJson = async (rawDocument: string): Promise<Record<string, any>> => {
1✔
61
  // convert the raw xdita document to jdita
62
  const jdita = await xditaToJdita(rawDocument);
1✔
63

64
  // convert the jdita document to prosemirror state save
65
  const prosemirrorJson = await jditaToProsemirrorJson(jdita);
1✔
66

67
  return prosemirrorJson;
1✔
68
};
69

70
/**
71
 * Fetches a raw document from a GitHub repository and transforms it into a ProseMirror JSON document.
72
 *
73
 * @param config - configuration
74
 * @param ghrepo - The GitHub repository from which to fetch the document.
75
 * @param source - The source path of the document within the repository.
76
 * @param branch - The branch from which to fetch the document.
77
 * @returns A promise that resolves to the transformed ProseMirror JSON document.
78
 */
79
export const fetchAndTransform = async (config: Config, ghrepo: string, source: string, branch: string, referer: string) => {
1✔
80
  const rawDoc = await fetchRawDocumentFromGitHub(config, ghrepo, source, branch);
×
81
  // update the document with the relative path
82

NEW
83
  const updatedDoc = rawDoc.replace(/href="([^"]+)"/g, (_match, url) => {
×
84
    // https://www.npmjs.com/package/urijs
NEW
85
    return `href="${urijs(url).absoluteTo(referer).href()}"`;
×
86
  });
87

NEW
88
  const jsonDoc = await transformGitHubDocumentToProsemirrorJson(updatedDoc);
×
UNCOV
89
  return jsonDoc;
×
90
};
91

92
/**
93
 * Exchanges an OAuth code for an access token.
94
 *
95
 * @param config - configuration
96
 * @param localization - localization
97
 * @param code - The OAuth code to exchange for an access token.
98
 * @returns A promise that resolves to the access token as a string.
99
 * @throws Will throw an error if the fetch request fails or if the response is not in the expected format.
100
 */
101
export const exchangeOAuthCodeForAccessToken = async (config: Config, localization: Localization, code: string): Promise<{token: string, installation: boolean}> => {
1✔
102
  // build the URL to exchange the code for an access token
103
  const url = config.server.api.baseUrl + config.server.api.endpoint.token + `?code=${code}`;
×
104
  // fetch the access token
105
  const response = await fetch(url);
×
106

107
  // TODO (AvC): This error type might be changed to be more specific depending on
108
  // further error handling
109
  if (!response.ok) {
×
110
    showToast(localization.t("error.toastGitHubToken") + response.statusText, 'error');
×
111
  }
112

113
  const json = await response.json();
×
114
  //TODO: Handle errors
115
  return {
×
116
    token: json.token,
117
    installation: json.installation
118
  };
119
};
120

121
/**
122
 * Fetches user information from the backend API.
123
 *
124
 * @param config - configuration
125
 * @param localization - localization
126
 * @param token - The authorization token to access the GitHub API.
127
 * @returns A promise that resolves to a record containing user information.
128
 */
129
export const getUserInfo = async (config: Config, localization: Localization, token: string): Promise<Record<string, string>> => {
3✔
130
  const url = config.server.api.baseUrl + config.server.api.endpoint.user;
3✔
131
  const response = await fetch(url, {
3✔
132
    headers: {
133
      'authorization': `Bearer ${token}`
134
    }
135
  });
136

137
  // TODO (AvC): This error type might be changed to be more specific depending on
138
  // further error handling
139
  if (!response.ok) {
3✔
140
    showToast(localization.t("error.toastGitHubUserEndpoint") + response.statusText, 'error');
1✔
141
  }
142
  const json = await response.json();
2✔
143
  return json;
2✔
144
};
145

146
/**
147
 * Publishes a document to a specified GitHub repository.
148
 * Makes a POST request to the `/api/github/integration` endpoint with the necessary details to create a pull request.
149
 *
150
 * @param config - configuration
151
 * @param localization - localization
152
 * @param ghrepo - The GitHub repository in the format "owner/repo".
153
 * @param source - The path to the source document.
154
 * @param branch - The branch used as base for the PR.
155
 * @param title - The title of the pull request and the commit message.
156
 * @param desc - The description of the pull request.
157
 * @param changedDocument - The content of the changed document.
158
 * @returns A promise that resolves when the document has been published.
159
 */
160
export const createPrFromContribution = async (config: Config, localization: Localization, ghrepo: string, source: string, branch: string, changedDocument: string, title: string, desc: string): Promise<string> => {
1✔
161
  const authenticatedUserInfo = await getUserInfo(config, localization, localStorage.getItem('token') as string);
1✔
162

163
  const owner = ghrepo.split('/')[0];
1✔
164
  const repo = ghrepo.split('/')[1];
1✔
165
  const newOwner = authenticatedUserInfo.login;
1✔
166
  const date = new Date();
1✔
167
  const newBranch = config.git.branchPrefix + `${date.getFullYear()}${date.getMonth()}${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}`;
1✔
168
  const commitMessage = title;
1✔
169
  const path = source;
1✔
170
  const content = changedDocument;
1✔
171
  const change = {
1✔
172
    path,
173
    content
174
  };
175
  const body = `${desc}` + config.git.commitMessageSuffix;
1✔
176
  // get the token from the local storage
177
  const token = localStorage.getItem('token');
1✔
178
  // make a post request to  /api/github/integration
179
  const response = await fetch(config.server.api.baseUrl + config.server.api.endpoint.integration, {
1✔
180
    method: 'POST',
181
    headers: {
182
      'Content-Type': 'application/json',
183
      'Authorization': `Bearer ${token}`
184
    },
185
    body: JSON.stringify({
186
      owner,
187
      repo,
188
      newOwner,
189
      branch,
190
      newBranch,
191
      commitMessage,
192
      change,
193
      title,
194
      body
195
    })
196
  });
197

198
  // TODO (AvC): This error type might be changed to be more specific depending on
199
  // further error handling
200
  if (!response.ok) {
1!
201
    showToast(localization.t("error.toastGitHubPR") + response.statusText, 'error');
×
202
  }
203

204
  const json = await response.json();
1✔
205
  return json.url;
1✔
206
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc