js-base64#Base64 TypeScript Examples

The following examples show how to use js-base64#Base64. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: senderAddressEncodeDecode.ts    From heimdall with MIT License 6 votes vote down vote up
decodeUnpureAliasValue = (
  unpureAliasValue: string
): DecodedSenderAddress => {
  // This works because there is no "+" character in Base64 characters
  const [aliasValue, encodedSenderAddress] = unpureAliasValue.split("+");

  return {
    aliasValue: aliasValue,
    senderAddress:
      encodedSenderAddress === undefined
        ? "" // Don't attempt to decode undefined
        : Base64.decode(encodedSenderAddress)
  };
}
Example #2
Source File: global.ts    From nebula-studio with Apache License 2.0 6 votes vote down vote up
login = async (payload: { host: string; username: string; password: string }) => {
    const { host, username, password } = payload;
    const [address, port] = host.replace(/^https?:\/\//, '').split(':');
    const { code, data } = (await service.connectDB(
      {
        address,
        port: +port,
      },
      {
        trackEventConfig: {
          category: 'user',
          action: 'sign_in',
        },
        headers: {
          Authorization: `Bearer ${Base64.encode(`${username}:${password}`)}`,
        },
      },
    )) as any;
    if (code === 0) {
      message.success(intl.get('configServer.success'));
      cookies.set('nh', host);
      cookies.set('nu', username);
      sessionStorage.setItem('curAccount', Base64.encode(`${username}:${host}`));
      sessionStorage.setItem('nebulaVersion', data.version);
      this.update({ _host: host, _username: username, nebulaVersion: data.version });
      return true;
    }

    this.update({ _host: '', _username: '' });
    cookies.remove('nh');
    cookies.remove('nu');
    sessionStorage.removeItem('nebulaVersion');
    sessionStorage.removeItem('curAccount');
    return false;
  };
Example #3
Source File: ProxyURI.ts    From shadowsocks-electron with GNU General Public License v3.0 6 votes vote down vote up
static parseSSRContent(uri: string): Proxy | null {
    let decoded = Base64.decode(uri);
    let coreRegex = new RegExp(`^(.+):(\\d+):(.*):(.+):(.*):(${ProxyURI.base64URLSafePattern})`, "gi");
    let coreMatch = coreRegex.exec(decoded);
    if (coreMatch && coreMatch[1] && coreMatch[2] && coreMatch[3] && coreMatch[4] && coreMatch[5] && coreMatch[6]) {
      let base64Password = coreMatch[6];
      let password = Base64.decode(base64Password);
      if (!password) {
        return null;
      }
      let proxy = new Proxy(ProxyScheme.SSR, coreMatch[1], Number(coreMatch[2]), coreMatch[4].toLowerCase());
      proxy.type = 'ssr';
      proxy.protocol = coreMatch[3].toLowerCase();
      proxy.obfs = coreMatch[5].toLowerCase();
      proxy.password = password;
      let obfsParamRegex = new RegExp(`obfsparam=(${ProxyURI.base64URLSafePattern})`, "gi");
      let obfsParamMatch = obfsParamRegex.exec(decoded);
      if (obfsParamMatch && obfsParamMatch[1]) {
        proxy.obfsParam = Base64.decode(obfsParamMatch[1]);
      }
      let protocolParamRegex = new RegExp(`protoparam=(${ProxyURI.base64URLSafePattern})`, "gi");
      let protocolParamMatch = protocolParamRegex.exec(decoded);
      if (protocolParamMatch && protocolParamMatch[1]) {
        proxy.protocolParam = Base64.decode(protocolParamMatch[1]);
      }
      let remarkRegex = new RegExp(`remarks=(${ProxyURI.base64URLSafePattern})`, "gi");
      let remarkMatch = remarkRegex.exec(decoded);
      if (remarkMatch && remarkMatch[1]) {
        proxy.remark = Base64.decode(remarkMatch[1]);
      }
      return proxy;
    }
    return null;
  }
Example #4
Source File: ProxyURI.ts    From shadowsocks-electron with GNU General Public License v3.0 6 votes vote down vote up
static generateSSR(host: string, port: number, method: string, password: string, remark?: string, protocol?: string, protocolParam?: string, obfs?: string, obfsParam?: string): string {
    let mainComponents = [host, port, (protocol || "origin").toLowerCase(), method.toLowerCase(), (obfs || "plain").toLowerCase(), Base64.encodeURI(password)];
    let paramComponents = new Map<string, string>()
    if (protocolParam) {
      paramComponents.set("protoparam", Base64.encodeURI(protocolParam));
    }
    if (obfsParam) {
      paramComponents.set("obfsparam", Base64.encodeURI(obfsParam));
    }
    if (remark) {
      paramComponents.set("remarks", Base64.encodeURI(remark));
    }
    let path = mainComponents.join(":");
    let params = Array.from(paramComponents).map(([key, value]) => (key + "=" + value)).join("&");
    let uri = path;
    if (params.length > 0) {
      uri += "/?" + params;
    }
    uri = Base64.encodeURI(uri);
    return ProxyScheme.SSR + uri;
  }
Example #5
Source File: ProxyURI.ts    From shadowsocks-electron with GNU General Public License v3.0 6 votes vote down vote up
static generateSS(host: string, port: number, method: string, password: string, remark?: string, isSIP002: boolean = true): string {
    if (isSIP002) {
      let rawUserInfo = method.toLowerCase() + ":" + password;
      let encodedUserInfo = Base64.encode(rawUserInfo);
      let uri = ProxyScheme.SS + encodedUserInfo + "@" + host + ":" + port;
      if (remark) {
        uri += "#" + encodeURI(remark);
      }
      return uri;
    } else {
      let rawURI = method.toLowerCase() + ":" + password + "@" + host + ":" + port;
      let uri = ProxyScheme.SS + Base64.encode(rawURI);
      if (remark) {
        uri += "#" + remark;
      }
      return uri;
    }
  }
Example #6
Source File: editor.ts    From excalidraw-vscode with MIT License 6 votes vote down vote up
private async buildHtmlForWebview(config: any): Promise<string> {
    const publicUri = vscode.Uri.joinPath(this.context.extensionUri, "public");
    const content = await vscode.workspace.fs.readFile(
      vscode.Uri.joinPath(publicUri, "index.html")
    );
    let html = this.textDecoder.decode(content);

    html = html.replace(
      "{{data-excalidraw-config}}",
      Base64.encode(JSON.stringify(config))
    );

    html = html.replace(
      "{{excalidraw-asset-path}}",
      `${this.webview
        .asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, "public"))
        .toString()}/`
    );

    return this.fixLinks(html, publicUri);
  }
Example #7
Source File: convertMetadata.ts    From nice-grpc with MIT License 6 votes vote down vote up
export function convertMetadataFromGrpcWeb(
  grpcMetadata: grpc.Metadata,
): Metadata {
  const metadata = Metadata();

  for (const [key, values] of Object.entries(grpcMetadata.headersMap)) {  
    metadata.set(
      key,
      key.endsWith('-bin')
        ? values.map(value => Base64.toUint8Array(value))
        : values,
    );
  }

  return metadata;
}
Example #8
Source File: convertMetadata.ts    From nice-grpc with MIT License 6 votes vote down vote up
export function convertMetadataToGrpcWeb(metadata: Metadata): grpc.Metadata {
  const grpcMetadata = new grpc.Metadata();

  for (const [key, values] of metadata) {
    for (const value of values) {
      grpcMetadata.append(
        key,
        typeof value === 'string' ? value : Base64.fromUint8Array(value),
      );
    }
  }

  return grpcMetadata;
}
Example #9
Source File: index.tsx    From excalidraw-vscode with MIT License 5 votes vote down vote up
function getExcalidrawConfig(rootElement: HTMLElement) {
  const b64Config = rootElement.getAttribute("data-excalidraw-config");
  if (!b64Config) {
    throw Error("data-excalidraw-config attribute is missing");
  }
  const strConfig = Base64.decode(b64Config);
  return JSON.parse(strConfig);
}
Example #10
Source File: senderAddressEncodeDecode.ts    From heimdall with MIT License 5 votes vote down vote up
encodeUnpureAliasValue = (
  aliasValue: string,
  originalSenderAddress: string
): string => {
  const encodedSenderAddress = Base64.encode(originalSenderAddress);
  return `${aliasValue}+${encodedSenderAddress}`;
}
Example #11
Source File: kubernetesTrainingService.ts    From AIPerf with MIT License 5 votes vote down vote up
protected async createAzureStorage(vaultName: string, valutKeyName: string): Promise<void> {
        try {
            const result: any = await cpp.exec(`az keyvault secret show --name ${valutKeyName} --vault-name ${vaultName}`);
            if (result.stderr) {
                const errorMessage: string = result.stderr;
                this.log.error(errorMessage);

                return Promise.reject(errorMessage);
            }
            const storageAccountKey: any = JSON.parse(result.stdout).value;
            if (this.azureStorageAccountName === undefined) {
                throw new Error('azureStorageAccountName not initialized!');
            }
            //create storage client
            this.azureStorageClient = azureStorage.createFileService(this.azureStorageAccountName, storageAccountKey);
            await AzureStorageClientUtility.createShare(this.azureStorageClient, this.azureStorageShare);
            //create sotrage secret
            this.azureStorageSecretName = String.Format('nni-secret-{0}', uniqueString(8)
                                                                            .toLowerCase());
            await this.genericK8sClient.createSecret(
                {
                    apiVersion: 'v1',
                    kind: 'Secret',
                    metadata: {
                        name: this.azureStorageSecretName,
                        namespace: 'default',
                        labels: {
                            app: this.NNI_KUBERNETES_TRIAL_LABEL,
                            expId: getExperimentId()
                        }
                    },
                    type: 'Opaque',
                    data: {
                        azurestorageaccountname: Base64.encode(this.azureStorageAccountName),
                        azurestorageaccountkey: Base64.encode(storageAccountKey)
                    }
                }
            );
        } catch (error) {
            this.log.error(error);

            return Promise.reject(error);
        }

        return Promise.resolve();
    }
Example #12
Source File: HaloRequestConfigBuilder.ts    From js-sdk with MIT License 5 votes vote down vote up
private buildHeaders(params: { basicAuth?: BasicAuth; userAgent?: string }): any {
    const { basicAuth, userAgent } = params
    const basicAuthHeaders = basicAuth
      ? {
          Authorization: `Basic ${Base64.encode(`${basicAuth.username}:${basicAuth.password}`)}`,
        }
      : {}
    const platformDepsHeaders = platformDeps.buildHeaders({ userAgent })
    const commonHeaders = { ...platformDepsHeaders, ...basicAuthHeaders }

    if (!this.auth) {
      return {}
    }

    switch (this.auth.type) {
      case 'password': {
        return {
          ...commonHeaders,
          Authorization: Base64.encode(`${this.auth.username}:${this.auth.password}`),
        }
      }
      case 'adminToken': {
        const adminToken = this.auth.adminToken
        return {
          ...commonHeaders,
          'Admin-Authorization': adminToken,
        }
      }
      case 'apiToken': {
        const apiToken = this.auth.apiToken
        if (Array.isArray(apiToken)) {
          return {
            ...commonHeaders,
            'API-Authorization': apiToken.join(','),
          }
        }
        return { ...commonHeaders, 'API-Authorization': apiToken }
      }
      case 'oAuthToken': {
        return {
          ...commonHeaders,
          Authorization: `Bearer ${this.auth.oAuthToken}`,
        }
      }
      case 'customizeAuth': {
        return {
          ...commonHeaders,
          [this.auth.authHeader]: this.auth.getToken(),
        }
      }
      default: {
        // https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest
        return { ...commonHeaders, 'X-Requested-With': 'XMLHttpRequest' }
      }
    }
  }
Example #13
Source File: ProxyURI.ts    From shadowsocks-electron with GNU General Public License v3.0 5 votes vote down vote up
static parseSSContent(uri: string): Proxy | null {
    // Try SIP 002 first
    let sip002Regex = new RegExp(`^(${ProxyURI.base64Pattern})@(.+?):(\\d+)(/\?[^#\\s]+?)?(#(.+))?$`, "gi")
    let match = sip002Regex.exec(uri)
    if (match && match[2] && match[3]) {
      let proxy = new Proxy(ProxyScheme.SS, match[2], Number(match[3]));
      proxy.type = 'ss';
      if (match[6]) {
        proxy.remark = decodeURI(match[6]);
      }
      let userInfo = Base64.decode(match[1]);
      let userInfoRegex = /^(.+?):(.+)/gi
      let userInfoMatch = userInfoRegex.exec(userInfo);
      if (userInfoMatch && userInfoMatch[1] && userInfoMatch[2]) {
        proxy.authscheme = userInfoMatch[1].toLowerCase();
        proxy.password = userInfoMatch[2];
        return proxy;
      }
      return null;
    }

    // Try legacy
    let legacyRegex = new RegExp(`^(${ProxyURI.base64Pattern})(#(.+))?$`, "gi");
    match = legacyRegex.exec(uri)
    if (match && match.length >= 2) {
      let proxy = new Proxy(ProxyScheme.SS);
      proxy.type = 'ss';
      proxy.remark = match[3];
      let core = Base64.decode(match[1]);
      // No "$" at the end is due to ShadowsocksX-NG compatibility issue
      // ShadowsocksX-NG will append a remark like "?remark=xxxxx"
      let mainRegex = /^(.+?):(.+)@(.+?):(\d+)/gi
      let coreComps = mainRegex.exec(core);
      if (coreComps && coreComps[1] && coreComps[2] && coreComps[3] && coreComps[4]) {
        proxy.host = coreComps[3];
        proxy.port = Number(coreComps[4]);
        proxy.authscheme = coreComps[1].toLowerCase();
        proxy.password = coreComps[2];
        return proxy;
      }
      return null;
    }

    return null;
  }
Example #14
Source File: dataHelper.ts    From airmessage-web with Apache License 2.0 5 votes vote down vote up
export function decodeBase64(value: string): ArrayBuffer {
	return Base64.toUint8Array(value);
}
Example #15
Source File: ProxyURI.ts    From shadowsocks-electron with GNU General Public License v3.0 5 votes vote down vote up
static parseHTTPContent(scheme: ProxyScheme, uri: string, isBase64: boolean = false): Proxy | null {
    let parseRemarks = function(uri: string) {
      let remarkRegex = new RegExp(`remarks=([^=/:?&]+)`, "gi");
      let remarkMatch = remarkRegex.exec(uri);
      if (remarkMatch && remarkMatch[1]) {
        return decodeURIComponent(remarkMatch[1]);
      }
      return undefined;
    }
    // Plain Style: http://1.2.3.4:8383
    let plainRegex = new RegExp(`^([^:@]+):(\\d+)`, "gi");
    let plainMatch = plainRegex.exec(uri);
    if (plainMatch && plainMatch[1] && plainMatch[2]) {
      let proxy = new Proxy(scheme, plainMatch[1], Number(plainMatch[2]));
      proxy.remark = parseRemarks(uri);
      return proxy;
    }
    // Auth Style: http://username(url encode):pass(url encode)@1.2.3.4:8383
    let authRegex = new RegExp(`^([^:@]*):([^:@]*)@([^:@]+):(\\d+)`, "gi");
    let authMatch = authRegex.exec(uri);
    if (authMatch && authMatch[1] && authMatch[2] && authMatch[3] && authMatch[4]) {
      let proxy = new Proxy(scheme, authMatch[3], Number(authMatch[4]));
      proxy.type = 'http';
      proxy.user = decodeURIComponent(authMatch[1]);
      proxy.password = decodeURIComponent(authMatch[2]);
      proxy.remark = parseRemarks(uri);
      return proxy;
    }
    // Base64 Style: http://MS4yLjMuNDo4Mzgz
    if (!isBase64) {
      let base64Regex = new RegExp(`^(${ProxyURI.base64URLSafePattern})`, "gi");
      let base64Match = base64Regex.exec(uri);
      if (base64Match) {
        let decoded = Base64.decode(uri);
        let proxy = this.parseHTTPContent(scheme, decoded, true);
        if (proxy) {
          proxy.type = 'http';
          proxy.remark = parseRemarks(uri);
        }
        return proxy;
      }
    }
    return null;
  }
Example #16
Source File: dataHelper.ts    From airmessage-web with Apache License 2.0 5 votes vote down vote up
export function encodeBase64(value: ArrayBuffer): string {
	return Base64.fromUint8Array(new Uint8Array(value));
}
Example #17
Source File: HaloRequestConfigBuilder.test.ts    From js-sdk with MIT License 4 votes vote down vote up
describe('Headers', () => {
  const baseUrl = 'https://example.halo.run'

  it('Basic Password auth', async () => {
    const USERNAME = 'user'
    const PASSWORD = 'password'
    const haloRequestConfigBuilder = new HaloRequestConfigBuilder({
      baseUrl,
      auth: {
        type: 'password',
        username: USERNAME,
        password: PASSWORD,
      },
    })
    const requestConfig = await haloRequestConfigBuilder.build('get', '/v1/record.json', {})
    expect(requestConfig.headers).toStrictEqual({
      'User-Agent': expectedDefaultUa,
      Authorization: Base64.encode(`${USERNAME}:${PASSWORD}`),
    })
  })

  it('AdminToken auth', async () => {
    const API_TOKEN = 'ApiToken'
    const haloRequestConfigBuilder = new HaloRequestConfigBuilder({
      baseUrl,
      auth: {
        type: 'adminToken',
        adminToken: API_TOKEN,
      },
    })
    const requestConfig = await haloRequestConfigBuilder.build('get', '/v1/record.json', {})
    expect(requestConfig.headers).toStrictEqual({
      'User-Agent': expectedDefaultUa,
      'Admin-Authorization': API_TOKEN,
    })
  })

  it('ApiToken auth', async () => {
    const API_TOKEN = 'ApiToken'
    const haloRequestConfigBuilder = new HaloRequestConfigBuilder({
      baseUrl,
      auth: {
        type: 'apiToken',
        apiToken: API_TOKEN,
      },
    })
    const requestConfig = await haloRequestConfigBuilder.build('get', '/v1/record.json', {})
    expect(requestConfig.headers).toStrictEqual({
      'User-Agent': expectedDefaultUa,
      'API-Authorization': API_TOKEN,
    })
  })

  it('ApiToken auth using multiple tokens as comma-separated string', async () => {
    const API_TOKEN1 = 'ApiToken1'
    const API_TOKEN2 = 'ApiToken2'
    const haloRequestConfigBuilder = new HaloRequestConfigBuilder({
      baseUrl,
      auth: {
        type: 'apiToken',
        apiToken: `${API_TOKEN1},${API_TOKEN2}`,
      },
    })
    const requestConfig = await haloRequestConfigBuilder.build('get', '/v1/record.json', {})
    expect(requestConfig.headers).toStrictEqual({
      'User-Agent': expectedDefaultUa,
      'API-Authorization': `${API_TOKEN1},${API_TOKEN2}`,
    })
  })

  it('ApiToken auth using multiple tokens as array', async () => {
    const API_TOKEN1 = 'ApiToken1'
    const API_TOKEN2 = 'ApiToken2'
    const haloRequestConfigBuilder = new HaloRequestConfigBuilder({
      baseUrl,
      auth: {
        type: 'apiToken',
        apiToken: [API_TOKEN1, API_TOKEN2],
      },
    })
    const requestConfig = await haloRequestConfigBuilder.build('get', '/v1/record.json', {})
    expect(requestConfig.headers).toStrictEqual({
      'User-Agent': expectedDefaultUa,
      'API-Authorization': `${API_TOKEN1},${API_TOKEN2}`,
    })
  })

  it('Session auth', async () => {
    const haloRequestConfigBuilder = new HaloRequestConfigBuilder({
      baseUrl,
      auth: {
        type: 'session',
      },
    })
    const requestConfig = await haloRequestConfigBuilder.build('get', '/v1/record.json', {})
    expect(requestConfig.headers).toStrictEqual({
      'User-Agent': expectedDefaultUa,
      'X-Requested-With': 'XMLHttpRequest',
    })
  })

  it('OAuth token auth', async () => {
    const oAuthToken = 'oauth-token'
    const haloRequestConfigBuilder = new HaloRequestConfigBuilder({
      baseUrl,
      auth: {
        type: 'oAuthToken',
        oAuthToken,
      },
    })
    const requestConfig = await haloRequestConfigBuilder.build('get', '/v1/record.json', {})
    expect(requestConfig.headers).toStrictEqual({
      Authorization: `Bearer ${oAuthToken}`,
      'User-Agent': expectedDefaultUa,
    })
  })

  it('Customizer auth', async () => {
    const adminToken = 'admin-token-12345'
    const haloRequestConfigBuilder = new HaloRequestConfigBuilder({
      baseUrl,
      auth: {
        type: 'customizeAuth',
        authHeader: 'Admin-Authorization',
        getToken() {
          return adminToken
        },
      },
    })
    const requestConfig = await haloRequestConfigBuilder.build('get', '/v1/record.json', {})
    expect(requestConfig.headers).toStrictEqual({
      'Admin-Authorization': adminToken,
      'User-Agent': expectedDefaultUa,
    })
  })

  it('Basic auth', async () => {
    const basicAuth = { username: 'user', password: 'password' }
    const haloRequestConfigBuilder = new HaloRequestConfigBuilder({
      baseUrl,
      basicAuth,
      auth: {
        type: 'session',
      },
    })
    const requestConfig = await haloRequestConfigBuilder.build('get', '/v1/record.json', {})
    expect(requestConfig.headers).toStrictEqual({
      Authorization: `Basic ${Base64.encode('user:password')}`,
      'User-Agent': expectedDefaultUa,
      'X-Requested-With': 'XMLHttpRequest',
    })
  })

  it('should not include User-Agent for browser enviroment', async () => {
    injectPlatformDeps(browserDeps)
    const haloRequestConfigBuilder = new HaloRequestConfigBuilder({
      baseUrl,
      auth: {
        type: 'session',
      },
    })
    const requestConfig = await haloRequestConfigBuilder.build('get', '/v1/record.json', {})
    expect(requestConfig.headers['User-Agent']).toBeUndefined()
  })
})
Example #18
Source File: publish-dialog.tsx    From bext with MIT License 4 votes vote down vote up
PublishDialog: FC<{ hide?: () => void }> = ({ hide }) => {
  const { draft } = useDraft();
  const { notify, dismissNotification } = useNotifications();
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(false);

  const onPublish = () => {
    const notifyId = uniqueId('export-notify');
    const loading = (message: string) =>
      notify({
        status: 'loading',
        message,
        dismissAfter: 0,
        dismissible: false,
        id: notifyId,
      });
    const branchName = Math.random().toString(16).slice(2);
    const user = user$.getValue()!.user!;
    const octokit = octokit$.getValue()!;
    setLoading(true);

    of(draft!)
      .pipe(
        switchMap((draft) => {
          if (!(draft.id && draft.name && draft.version)) {
            return throwError(() => new Error('请填写完整 ID,名称,版本号'));
          }
          loading('编译中');
          return from(
            excuteCompile({
              meta: {
                id: draft.id,
                name: draft.name,
                version: draft.version!,
                source: draft.source!,
                defaultConfig: draft.defaultConfig,
              },
            }),
          ).pipe(
            catchError(() =>
              throwError(() => new Error('编译错误,请打开控制台查看详情')),
            ),
            switchMap(() => {
              loading('获取仓库信息');
              return from(
                octokit.repos.get({
                  owner: user.login!,
                  repo: packageJson.metaRepository.repo,
                }),
              ).pipe(
                catchError((error) => {
                  if (error.status === 404) {
                    loading('Fork 仓库');
                    return from(
                      octokit.repos.createFork({
                        owner: packageJson.metaRepository.owner,
                        repo: packageJson.metaRepository.repo,
                      }),
                    ).pipe(
                      concatMap(() => {
                        loading('查询 Fork 结果');
                        return timer(5000, 10000).pipe(
                          switchMap(() =>
                            from(
                              octokit.repos.get({
                                owner: user.login!,
                                repo: packageJson.metaRepository.repo,
                              }),
                            ).pipe(catchError(() => EMPTY)),
                          ),
                          take(1),
                        );
                      }),
                    );
                  }
                  return throwError(() => new Error('查询仓库信息失败'));
                }),
              );
            }),
            switchMap(({ data: repo }) => {
              loading('创建分支');
              return from(
                octokit.git.createRef({
                  owner: repo.owner.login,
                  repo: repo.name,
                  ref: `refs/heads/${branchName}`,
                  sha: packageJson.metaRepository.base,
                }),
              );
            }),
            switchMap(() => {
              loading('同步主分支');
              return from(
                octokit.repos.mergeUpstream({
                  owner: user.login!,
                  repo: packageJson.metaRepository.repo,
                  branch: branchName,
                }),
              );
            }),
            switchMap(() => {
              loading('获取文件信息');
              return from(
                octokit.repos.getContent({
                  owner: user.login,
                  repo: packageJson.metaRepository.repo,
                  path: `meta/${draft.id}.json`,
                  ref: branchName,
                }),
              ).pipe(
                map(({ data }) =>
                  Array.isArray(data) ? data[0].sha : data.sha,
                ),
                catchError((err) =>
                  err?.status === 404 ? of(undefined) : throwError(() => err),
                ),
              );
            }),
            switchMap((sha) => {
              const prepareDraft = omit(cloneDeep(draft), 'id');
              prepareDraft.detail = DOMPurify.sanitize(
                prepareDraft.detail || '',
              );
              return from(
                octokit.repos.createOrUpdateFileContents({
                  owner: user.login,
                  repo: packageJson.metaRepository.repo,
                  path: `meta/${draft.id}.json`,
                  message,
                  content: Base64.encode(JSON.stringify(prepareDraft)),
                  sha,
                  branch: branchName,
                }),
              );
            }),
            switchMap(() =>
              from(
                octokit.pulls.create({
                  owner: packageJson.metaRepository.owner,
                  repo: packageJson.metaRepository.repo,
                  title: `[${draft.name}] ${draft.synopsis}`,
                  head: `${user.login}:${branchName}`,
                  base: 'master',
                  maintainer_can_modify: true,
                }),
              ),
            ),
          );
        }),
        finalize(() => {
          dismissNotification(notifyId);
          setLoading(false);
          hide?.();
        }),
        catchError((err) => {
          notify({
            status: 'error',
            message: err?.message || err?.toString(),
            dismissible: true,
            dismissAfter: 3000,
          });
          return EMPTY;
        }),
      )
      .subscribe(() => {
        notify({
          status: 'success',
          message: '提交成功,请返回查看、预览',
        });
      });
  };

  return (
    <>
      <TextField
        description="将会在切换版本时展示"
        value={message}
        onChange={(_, text) => setMessage(text || '')}
        disabled={loading}
      />
      <DialogFooter>
        <PrimaryButton
          className="ml-auto"
          onClick={onPublish}
          disabled={loading || !message.length}
        >
          发布
        </PrimaryButton>
      </DialogFooter>
    </>
  );
}
Example #19
Source File: CatalogImportClient.ts    From backstage with Apache License 2.0 4 votes vote down vote up
// TODO: extract this function and implement for non-github
  private async submitGitHubPrToRepo(options: {
    owner: string;
    repo: string;
    title: string;
    body: string;
    fileContent: string;
    repositoryUrl: string;
    githubIntegrationConfig: GitHubIntegrationConfig;
  }): Promise<{ link: string; location: string }> {
    const {
      owner,
      repo,
      title,
      body,
      fileContent,
      repositoryUrl,
      githubIntegrationConfig,
    } = options;

    const { token } = await this.scmAuthApi.getCredentials({
      url: repositoryUrl,
      additionalScope: {
        repoWrite: true,
      },
    });

    const octo = new Octokit({
      auth: token,
      baseUrl: githubIntegrationConfig.apiBaseUrl,
    });

    const branchName = getBranchName(this.configApi);
    const fileName = getCatalogFilename(this.configApi);

    const repoData = await octo.repos
      .get({
        owner,
        repo,
      })
      .catch(e => {
        throw new Error(formatHttpErrorMessage("Couldn't fetch repo data", e));
      });

    const parentRef = await octo.git
      .getRef({
        owner,
        repo,
        ref: `heads/${repoData.data.default_branch}`,
      })
      .catch(e => {
        throw new Error(
          formatHttpErrorMessage("Couldn't fetch default branch data", e),
        );
      });

    await octo.git
      .createRef({
        owner,
        repo,
        ref: `refs/heads/${branchName}`,
        sha: parentRef.data.object.sha,
      })
      .catch(e => {
        throw new Error(
          formatHttpErrorMessage(
            `Couldn't create a new branch with name '${branchName}'`,
            e,
          ),
        );
      });

    await octo.repos
      .createOrUpdateFileContents({
        owner,
        repo,
        path: fileName,
        message: title,
        content: Base64.encode(fileContent),
        branch: branchName,
      })
      .catch(e => {
        throw new Error(
          formatHttpErrorMessage(
            `Couldn't create a commit with ${fileName} file added`,
            e,
          ),
        );
      });

    const pullRequestResponse = await octo.pulls
      .create({
        owner,
        repo,
        title,
        head: branchName,
        body,
        base: repoData.data.default_branch,
      })
      .catch(e => {
        throw new Error(
          formatHttpErrorMessage(
            `Couldn't create a pull request for ${branchName} branch`,
            e,
          ),
        );
      });

    return {
      link: pullRequestResponse.data.html_url,
      location: `https://${githubIntegrationConfig.host}/${owner}/${repo}/blob/${repoData.data.default_branch}/${fileName}`,
    };
  }