<commit_before>/**
 * Copyright (c) 2020-2021 Philippe Lieser
 *
 * This software is licensed under the terms of the MIT License.
 *
 * The above copyright and license notice shall be
 * included in all copies or substantial portions of the Software.
 */

// @ts-check

import ArhParser from "../../modules/arhParser.mjs.js";
import expect from "../helpers/chaiUtils.mjs.js";

describe("ARH Parser [unittest]", function () {
	describe("RFC 7601 Appendix B Example", function () {
		it("B.2.  Nearly Trivial Case; Service Provided, but No Authentication Done", function () {
			const res = ArhParser.parse(
				"Authentication-Results: example.org 1; none\r\n");
			expect(res.authserv_id).to.be.equal("example.org");
			expect(res.authres_version).to.be.equal(1);
			expect(res.resinfo.length).to.be.equal(0);
		});
		it("B.3.  Service Provided, Authentication Done", function () {
			const res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          spf=pass smtp.mailfrom=example.net\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.authres_version).to.be.equal(1);
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("spf");
			expect(res.resinfo[0]?.method_version).to.be.equal(1);
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.smtp.mailfrom).to.be.equal("example.net");
		});
		it("B.4.  Service Provided, Several Authentications Done, Single MTA", function () {
			let res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          auth=pass (cram-md5) smtp.auth=sender@example.net;\r\n" +
				"          spf=pass smtp.mailfrom=example.net\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(2);
			expect(res.resinfo[0]?.method).to.be.equal("auth");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.smtp.auth).to.be.equal("sender@example.net");
			expect(res.resinfo[1]?.method).to.be.equal("spf");
			expect(res.resinfo[1]?.result).to.be.equal("pass");
			expect(res.resinfo[1]?.propertys.smtp.mailfrom).to.be.equal("example.net");
			res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          sender-id=pass header.from=example.net\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("sender-id");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.from).to.be.equal("example.net");
		});
		it("B.5.  Service Provided, Several Authentications Done, Different MTAs", function () {
			let res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          sender-id=fail header.from=example.com;\r\n" +
				"          dkim=pass (good signature) header.d=example.com\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(2);
			expect(res.resinfo[0]?.method).to.be.equal("sender-id");
			expect(res.resinfo[0]?.result).to.be.equal("fail");
			expect(res.resinfo[0]?.propertys.header.from).to.be.equal("example.com");
			expect(res.resinfo[1]?.method).to.be.equal("dkim");
			expect(res.resinfo[1]?.result).to.be.equal("pass");
			expect(res.resinfo[1]?.propertys.header.d).to.be.equal("example.com");
			res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          auth=pass (cram-md5) smtp.auth=sender@example.com;\r\n" +
				"          spf=fail smtp.mailfrom=example.com\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(2);
			expect(res.resinfo[0]?.method).to.be.equal("auth");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.smtp.auth).to.be.equal("sender@example.com");
			expect(res.resinfo[1]?.method).to.be.equal("spf");
			expect(res.resinfo[1]?.result).to.be.equal("fail");
			expect(res.resinfo[1]?.propertys.smtp.mailfrom).to.be.equal("example.com");
		});
		it("B.6.  Service Provided, Multi-tiered Authentication Done", function () {
			let res = ArhParser.parse(
				'Authentication-Results: example.com;\r\n' +
				'      dkim=pass reason="good signature"\r\n' +
				'        header.i=@mail-router.example.net;\r\n' +
				'      dkim=fail reason="bad signature"\r\n' +
				'        header.i=@newyork.example.com\r\n');
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(2);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.reason).to.be.equal("good signature");
			expect(res.resinfo[0]?.propertys.header.i).to.be.equal("@mail-router.example.net");
			expect(res.resinfo[1]?.method).to.be.equal("dkim");
			expect(res.resinfo[1]?.result).to.be.equal("fail");
			expect(res.resinfo[1]?.reason).to.be.equal("bad signature");
			expect(res.resinfo[1]?.propertys.header.i).to.be.equal("@newyork.example.com");
			res = ArhParser.parse(
				"Authentication-Results: example.net;\r\n" +
				"      dkim=pass (good signature) header.i=@newyork.example.com\r\n");
			expect(res.authserv_id).to.be.equal("example.net");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.i).to.be.equal("@newyork.example.com");
		});
		it("B.7.  Comment-Heavy Example", function () {
			const res = ArhParser.parse(
				"Authentication-Results: foo.example.net (foobar) 1 (baz);\r\n" +
				"    dkim (Because I like it) / 1 (One yay) = (wait for it) fail\r\n" +
				"      policy (A dot can go here) . (like that) expired\r\n" +
				"      (this surprised me) = (as I wasn't expecting it) 1362471462\r\n");
			expect(res.authserv_id).to.be.equal("foo.example.net");
			expect(res.authres_version).to.be.equal(1);
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.method_version).to.be.equal(1);
			expect(res.resinfo[0]?.result).to.be.equal("fail");
			expect(res.resinfo[0]?.propertys.policy.expired).to.be.equal("1362471462");
		});
	});
	describe("Relaxed parsing", function () {
		it("Trailing ;", function () {
			const arh =
				"Authentication-Results: example.com;\r\n" +
				"          spf=pass smtp.mailfrom=example.net;\r\n";

			expect(() => ArhParser.parse(arh)).to.throw;

			const res = ArhParser.parse(arh, true);
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("spf");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
		});
		it("Property with / not in quotes ", function () {
			const arh =
				"Authentication-Results: example.com;\r\n" +
				"          dkim=pass header.b=gfT/i2HB\r\n";

			expect(() => ArhParser.parse(arh)).to.throw;

			const res = ArhParser.parse(arh, true);
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.b).to.be.equal("gfT/i2HB");
		});
	});
	describe("DKIM results", function () {
		it("AUID with local part", function () {
			const res = ArhParser.parse(
				"Authentication-Results: example.net;\r\n" +
				'      dkim=pass header.i=dkim+foo-bar@example.github.com\r\n');

			expect(res.authserv_id).to.be.equal("example.net");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.i).to.be.equal("dkim+foo-bar@example.github.com");
		});
		it("quoted SDID and AUID", function () {
			const res = ArhParser.parse(
				"Authentication-Results: example.net;\r\n" +
				'      dkim=pass header.d="github.com" header.i="dkim+foo-bar@example.github.com"\r\n');

			expect(res.authserv_id).to.be.equal("example.net");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.d).to.be.equal("github.com");
			expect(res.resinfo[0]?.propertys.header.i).to.be.equal("dkim+foo-bar@example.github.com");
		});
	});
});
<commit_msg>Add examples from RFC 8601 (#219)<commit_after>/**
 * Copyright (c) 2020-2022 Philippe Lieser
 *
 * This software is licensed under the terms of the MIT License.
 *
 * The above copyright and license notice shall be
 * included in all copies or substantial portions of the Software.
 */

// @ts-check

import ArhParser from "../../modules/arhParser.mjs.js";
import expect from "../helpers/chaiUtils.mjs.js";

describe("ARH Parser [unittest]", function () {
	describe("RFC 7601 Appendix B Example", function () {
		it("B.2.  Nearly Trivial Case; Service Provided, but No Authentication Done", function () {
			const res = ArhParser.parse(
				"Authentication-Results: example.org 1; none\r\n");
			expect(res.authserv_id).to.be.equal("example.org");
			expect(res.authres_version).to.be.equal(1);
			expect(res.resinfo.length).to.be.equal(0);
		});
		it("B.3.  Service Provided, Authentication Done", function () {
			const res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          spf=pass smtp.mailfrom=example.net\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.authres_version).to.be.equal(1);
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("spf");
			expect(res.resinfo[0]?.method_version).to.be.equal(1);
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.smtp.mailfrom).to.be.equal("example.net");
		});
		it("B.4.  Service Provided, Several Authentications Done, Single MTA", function () {
			let res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          auth=pass (cram-md5) smtp.auth=sender@example.net;\r\n" +
				"          spf=pass smtp.mailfrom=example.net\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(2);
			expect(res.resinfo[0]?.method).to.be.equal("auth");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.smtp.auth).to.be.equal("sender@example.net");
			expect(res.resinfo[1]?.method).to.be.equal("spf");
			expect(res.resinfo[1]?.result).to.be.equal("pass");
			expect(res.resinfo[1]?.propertys.smtp.mailfrom).to.be.equal("example.net");
			// From [RFC 7601]
			res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          sender-id=pass header.from=example.net\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("sender-id");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.from).to.be.equal("example.net");
			// From [RFC 8601]
			res = ArhParser.parse(
				"Authentication-Results: example.com; iprev=pass\r\n" +
				"          policy.iprev=192.0.2.200\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("iprev");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.policy.iprev).to.be.equal("192.0.2.200");
		});
		it("B.5.  Service Provided, Several Authentications Done, Different MTAs", function () {
			// From [RFC 7601]
			let res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          sender-id=fail header.from=example.com;\r\n" +
				"          dkim=pass (good signature) header.d=example.com\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(2);
			expect(res.resinfo[0]?.method).to.be.equal("sender-id");
			expect(res.resinfo[0]?.result).to.be.equal("fail");
			expect(res.resinfo[0]?.propertys.header.from).to.be.equal("example.com");
			expect(res.resinfo[1]?.method).to.be.equal("dkim");
			expect(res.resinfo[1]?.result).to.be.equal("pass");
			expect(res.resinfo[1]?.propertys.header.d).to.be.equal("example.com");
			// From [RFC 8601]
			res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          dkim=pass (good signature) header.d=example.com\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.d).to.be.equal("example.com");
			res = ArhParser.parse(
				"Authentication-Results: example.com;\r\n" +
				"          auth=pass (cram-md5) smtp.auth=sender@example.com;\r\n" +
				"          spf=fail smtp.mailfrom=example.com\r\n");
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(2);
			expect(res.resinfo[0]?.method).to.be.equal("auth");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.smtp.auth).to.be.equal("sender@example.com");
			expect(res.resinfo[1]?.method).to.be.equal("spf");
			expect(res.resinfo[1]?.result).to.be.equal("fail");
			expect(res.resinfo[1]?.propertys.smtp.mailfrom).to.be.equal("example.com");
		});
		it("B.6.  Service Provided, Multi-tiered Authentication Done", function () {
			let res = ArhParser.parse(
				'Authentication-Results: example.com;\r\n' +
				'      dkim=pass reason="good signature"\r\n' +
				'        header.i=@mail-router.example.net;\r\n' +
				'      dkim=fail reason="bad signature"\r\n' +
				'        header.i=@newyork.example.com\r\n');
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(2);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.reason).to.be.equal("good signature");
			expect(res.resinfo[0]?.propertys.header.i).to.be.equal("@mail-router.example.net");
			expect(res.resinfo[1]?.method).to.be.equal("dkim");
			expect(res.resinfo[1]?.result).to.be.equal("fail");
			expect(res.resinfo[1]?.reason).to.be.equal("bad signature");
			expect(res.resinfo[1]?.propertys.header.i).to.be.equal("@newyork.example.com");
			res = ArhParser.parse(
				"Authentication-Results: example.net;\r\n" +
				"      dkim=pass (good signature) header.i=@newyork.example.com\r\n");
			expect(res.authserv_id).to.be.equal("example.net");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.i).to.be.equal("@newyork.example.com");
		});
		it("B.7.  Comment-Heavy Example", function () {
			const res = ArhParser.parse(
				"Authentication-Results: foo.example.net (foobar) 1 (baz);\r\n" +
				"    dkim (Because I like it) / 1 (One yay) = (wait for it) fail\r\n" +
				"      policy (A dot can go here) . (like that) expired\r\n" +
				"      (this surprised me) = (as I wasn't expecting it) 1362471462\r\n");
			expect(res.authserv_id).to.be.equal("foo.example.net");
			expect(res.authres_version).to.be.equal(1);
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.method_version).to.be.equal(1);
			expect(res.resinfo[0]?.result).to.be.equal("fail");
			expect(res.resinfo[0]?.propertys.policy.expired).to.be.equal("1362471462");
		});
	});
	describe("Relaxed parsing", function () {
		it("Trailing ;", function () {
			const arh =
				"Authentication-Results: example.com;\r\n" +
				"          spf=pass smtp.mailfrom=example.net;\r\n";

			expect(() => ArhParser.parse(arh)).to.throw;

			const res = ArhParser.parse(arh, true);
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("spf");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
		});
		it("Property with / not in quotes ", function () {
			const arh =
				"Authentication-Results: example.com;\r\n" +
				"          dkim=pass header.b=gfT/i2HB\r\n";

			expect(() => ArhParser.parse(arh)).to.throw;

			const res = ArhParser.parse(arh, true);
			expect(res.authserv_id).to.be.equal("example.com");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.b).to.be.equal("gfT/i2HB");
		});
	});
	describe("DKIM results", function () {
		it("AUID with local part", function () {
			const res = ArhParser.parse(
				"Authentication-Results: example.net;\r\n" +
				'      dkim=pass header.i=dkim+foo-bar@example.github.com\r\n');

			expect(res.authserv_id).to.be.equal("example.net");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.i).to.be.equal("dkim+foo-bar@example.github.com");
		});
		it("quoted SDID and AUID", function () {
			const res = ArhParser.parse(
				"Authentication-Results: example.net;\r\n" +
				'      dkim=pass header.d="github.com" header.i="dkim+foo-bar@example.github.com"\r\n');

			expect(res.authserv_id).to.be.equal("example.net");
			expect(res.resinfo.length).to.be.equal(1);
			expect(res.resinfo[0]?.method).to.be.equal("dkim");
			expect(res.resinfo[0]?.result).to.be.equal("pass");
			expect(res.resinfo[0]?.propertys.header.d).to.be.equal("github.com");
			expect(res.resinfo[0]?.propertys.header.i).to.be.equal("dkim+foo-bar@example.github.com");
		});
	});
});
<|endoftext|>


<commit_before>clientSpecific = qx.core.Variant.select("qx.client", {
  "gecko|mshtml" : function() { geckoOrMshtml(); },
  "default" : function() { other(); }
});<commit_msg>Webkit instead of Mshtml to work with current jsoptimize<commit_after>clientSpecific = qx.core.Variant.select("qx.client", {
  "gecko|webkit" : function() { geckoOrWebkit(); },
  "default" : function() { other(); }
});<|endoftext|>


<commit_before>/* autogenerated by the update_version script */
exports.version=1602016603;
<commit_msg>new version<commit_after>/* autogenerated by the update_version script */
exports.version=1602401689;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const copyProjectTemplateAndReplace = require('../generator/copyProjectTemplateAndReplace');
const path = require('path');
const sharp = require('sharp');
const fs = require('fs');

/**
 * The eject command re-creates the `android` and `ios` native folders. Because native code can be
 * difficult to maintain, this new script allows an `app.json` to be defined for the project, which
 * is used to configure the native app.
 *
 * The `app.json` config may contain the following keys:
 *
 * - `name` - The short name used for the project, should be TitleCase
 * - `displayName` - The app's name on the home screen
 */

function eject() {

  const doesIOSExist = fs.existsSync(path.resolve('ios'));
  const doesAndroidExist = fs.existsSync(path.resolve('android'));
  if (doesIOSExist && doesAndroidExist) {
    console.error(
      'Both the iOS and Android folders already exist! Please delete `ios` and/or `android` ' +
      'before ejecting.'
    );
    process.exit(1);
  }

  let appConfig = null;
  try {
    appConfig = require(path.resolve('app.json'));
  } catch(e) {
    console.error(
      `Eject requires an \`app.json\` config file to be located at ` +
      `${path.resolve('app.json')}, and it must at least specify a \`name\` for the project ` +
      `name, and a \`displayName\` for the app's home screen label.`
    );
    process.exit(1);
  }

  const appName = appConfig.name;
  if (!appName) {
    console.error(
      `App \`name\` must be defined in the \`app.json\` config file to define the project name. `+
      `It must not contain any spaces or dashes.`
    );
    process.exit(1);
  }
  const displayName = appConfig.displayName;
  if (!displayName) {
    console.error(
      `App \`displayName\` must be defined in the \`app.json\` config file, to define the label ` +
      `of the app on the home screen.`
    );
    process.exit(1);
  }

  const appIcon = appConfig.icon;
  if(!appIcon) {
    console.error(
      'Please provide an icon for the app'
    );
    process.exit(1);
  }

  const templateOptions = { displayName };

  if (!doesIOSExist) {
    console.log('Generating the iOS folder.');
    copyProjectTemplateAndReplace(
      path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld', 'ios'),
      path.resolve('ios'),
      appName,
      appIcon,
      templateOptions
    );

    console.log('Setting Up App Icons.')
    const pictureSizes = [40, 60, 58, 87, 80, 120, 180];
    let contentPath = 'ios/SomeTest/Images.xcassets/AppIcon.appiconset/Contents.json';

    let fileNames = pictureSizes.reduce( (acc, size) => {
      let filePath = 'ios/SomeTest/Images.xcassets/AppIcon.appiconset/' + size + 'pt-' + appIcon;
      let fileName = size+'pt-'+appIcon;
      sharp(appIcon)
      .resize(size, size)
      .toFile(filePath, function(err) {
        if(err) throw err;
      });
      acc['SIZE_'+size] = fileName;
      return acc
    }, []);

    fs.readFile(contentPath, 'utf8', function (err, data) {
      if (err) throw err;
      let obj = JSON.parse(data);

      obj.images.map((image, key) => {
        let size = parseInt(image.size.split('x')[0]);
        let scale = parseInt(image.scale.replace('x', ''));
        let fileName = fileNames['SIZE_'+ scale*size];
        obj.images[key].filename = fileName;
        return obj;
      })
      console.log(obj);
      fs.writeFile(contentPath, JSON.stringify(obj), 'utf8', function(err){
        if(err) throw err;
      })
    });

  }

  if (!doesAndroidExist) {
    console.log('Generating the Android folder.');
    copyProjectTemplateAndReplace(
      path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld', 'android'),
      path.resolve('android'),
      appName,
      templateOptions
    );

    console.log('Setting up App Icons');
    const hdpiPath = 'android/app/src/main/res/mipmap-hdpi' + '/ic_launcher.png';
    const mdpiPath = 'android/app/src/main/res/mipmap-mdpi' + '/ic_launcher.png';
    const xhdpiPath = 'android/app/src/main/res/mipmap-xhdpi' + '/ic_launcher.png';
    const xxhdpiPath = 'android/app/src/main/res/mipmap-xxhdpi' + '/ic_launcher.png';

    const pictureSizes = [48, 72, 96, 144];
    const filePaths = [hdpiPath, mdpiPath, xhdpiPath, xxhdpiPath];

    filePaths.map((path) => {
      fs.unlink(path, (err) => {
        if(err) throw err;
      })
    })

    pictureSizes.map((size, key) => {
      console.log(filePaths[key], size);
      sharp(appIcon)
      .resize(size, size)
      .toFile(filePaths[key], function(err) {
        if (err) throw err;
      });
    });
  }

}

module.exports = {
  name: 'eject',
  description: 'Re-create the iOS and Android folders and native code',
  func: eject,
  options: [],
};
<commit_msg>removing a log<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const copyProjectTemplateAndReplace = require('../generator/copyProjectTemplateAndReplace');
const path = require('path');
const sharp = require('sharp');
const fs = require('fs');

/**
 * The eject command re-creates the `android` and `ios` native folders. Because native code can be
 * difficult to maintain, this new script allows an `app.json` to be defined for the project, which
 * is used to configure the native app.
 *
 * The `app.json` config may contain the following keys:
 *
 * - `name` - The short name used for the project, should be TitleCase
 * - `displayName` - The app's name on the home screen
 */

function eject() {

  const doesIOSExist = fs.existsSync(path.resolve('ios'));
  const doesAndroidExist = fs.existsSync(path.resolve('android'));
  if (doesIOSExist && doesAndroidExist) {
    console.error(
      'Both the iOS and Android folders already exist! Please delete `ios` and/or `android` ' +
      'before ejecting.'
    );
    process.exit(1);
  }

  let appConfig = null;
  try {
    appConfig = require(path.resolve('app.json'));
  } catch(e) {
    console.error(
      `Eject requires an \`app.json\` config file to be located at ` +
      `${path.resolve('app.json')}, and it must at least specify a \`name\` for the project ` +
      `name, and a \`displayName\` for the app's home screen label.`
    );
    process.exit(1);
  }

  const appName = appConfig.name;
  if (!appName) {
    console.error(
      `App \`name\` must be defined in the \`app.json\` config file to define the project name. `+
      `It must not contain any spaces or dashes.`
    );
    process.exit(1);
  }
  const displayName = appConfig.displayName;
  if (!displayName) {
    console.error(
      `App \`displayName\` must be defined in the \`app.json\` config file, to define the label ` +
      `of the app on the home screen.`
    );
    process.exit(1);
  }

  const appIcon = appConfig.icon;
  if(!appIcon) {
    console.error(
      'Please provide an icon for the app'
    );
    process.exit(1);
  }

  const templateOptions = { displayName };

  if (!doesIOSExist) {
    console.log('Generating the iOS folder.');
    copyProjectTemplateAndReplace(
      path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld', 'ios'),
      path.resolve('ios'),
      appName,
      appIcon,
      templateOptions
    );

    console.log('Setting Up App Icons.')
    const pictureSizes = [40, 60, 58, 87, 80, 120, 180];
    let contentPath = 'ios/SomeTest/Images.xcassets/AppIcon.appiconset/Contents.json';

    let fileNames = pictureSizes.reduce( (acc, size) => {
      let filePath = 'ios/SomeTest/Images.xcassets/AppIcon.appiconset/' + size + 'pt-' + appIcon;
      let fileName = size+'pt-'+appIcon;
      sharp(appIcon)
      .resize(size, size)
      .toFile(filePath, function(err) {
        if(err) throw err;
      });
      acc['SIZE_'+size] = fileName;
      return acc
    }, []);

    fs.readFile(contentPath, 'utf8', function (err, data) {
      if (err) throw err;
      let obj = JSON.parse(data);

      obj.images.map((image, key) => {
        let size = parseInt(image.size.split('x')[0]);
        let scale = parseInt(image.scale.replace('x', ''));
        let fileName = fileNames['SIZE_'+ scale*size];
        obj.images[key].filename = fileName;
        return obj;
      })
      fs.writeFile(contentPath, JSON.stringify(obj), 'utf8', function(err){
        if(err) throw err;
      })
    });

  }

  if (!doesAndroidExist) {
    console.log('Generating the Android folder.');
    copyProjectTemplateAndReplace(
      path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld', 'android'),
      path.resolve('android'),
      appName,
      templateOptions
    );

    console.log('Setting up App Icons');
    const hdpiPath = 'android/app/src/main/res/mipmap-hdpi' + '/ic_launcher.png';
    const mdpiPath = 'android/app/src/main/res/mipmap-mdpi' + '/ic_launcher.png';
    const xhdpiPath = 'android/app/src/main/res/mipmap-xhdpi' + '/ic_launcher.png';
    const xxhdpiPath = 'android/app/src/main/res/mipmap-xxhdpi' + '/ic_launcher.png';

    const pictureSizes = [48, 72, 96, 144];
    const filePaths = [hdpiPath, mdpiPath, xhdpiPath, xxhdpiPath];

    filePaths.map((path) => {
      fs.unlink(path, (err) => {
        if(err) throw err;
      })
    })

    pictureSizes.map((size, key) => {
      sharp(appIcon)
      .resize(size, size)
      .toFile(filePaths[key], function(err) {
        if (err) throw err;
      });
    });
  }

}

module.exports = {
  name: 'eject',
  description: 'Re-create the iOS and Android folders and native code',
  func: eject,
  options: [],
};
<|endoftext|>


<commit_before>"use strict";

define(['logManager',
    'clientUtil',
    'commonUtil',
    'js/ModelEditor3/DesignerControl',
    'js/DiagramDesigner/NodePropertyNames',
    'js/ModelEditor3/MetaDesignerControl.DEBUG',
    'css!ModelEditor3CSS/MetaDesignerControl'], function (logManager,
                                                     clientUtil,
                                                     commonUtil,
                                                     DesignerControl,
                                                     nodePropertyNames,
                                                     MetaDesignerControlDEBUG) {

    var MetaDesignerControl,
        __parent__ = DesignerControl,
        __parent_proto__ = DesignerControl.prototype,
        VALIDCHILDREN_TYPE_LINE_END = "diamond-wide-long",
        VALIDINHERITOR_TYPE_LINE_END = "block-wide-long",
        VALIDSOURCE_TYPE_LINE_END = "oval-wide-long",
        VALIDDESTINATION_TYPE_LINE_END = "open-wide-long",
        GENERAL_TYPE_LINE_END = "none",
        NOEND = "none",
        LOAD_EVENT_NAME = "load",
        SET_VALIDCHILDREN = 'ValidChildren',
        SET_VALIDSOURCE = 'ValidSource',
        SET_VALIDDESTINATION = 'ValidDestination',
        SET_VALIDINHERITOR = 'ValidInheritor',
        SET_GENERAL = 'General';

    MetaDesignerControl = function (options) {
        var self = this,
            $btnGroupConnectionType;

        options.loggerName = options.loggerName || "MetaDesignerControl";

        //execute parent's constructor
        __parent__.apply(this, [options]);

        this._setRelations = {};

        //override parent's event handlers
        this.designerCanvas.onSelectionDelete = function (idList) {
            var len = idList.length,
                desc;

            while (len--) {
                if (self._setRelations[idList[len]]) {
                    desc = self._setRelations[idList[len]];
                    self._client.removeMember(desc.owner, desc.member, desc.set);
                    delete self._setRelations[idList[len]];
                    self.designerCanvas.deleteComponent(idList[len]);

                }
            }
        };

        this.designerCanvas.onCreateNewConnection = function (params) {
            var type = params.metaInfo.type,
                sourceId = self._ComponentID2GmeID[params.src],
                targetId = self._ComponentID2GmeID[params.dst];

            //connDesc.type has special meaning: inheritance, containment, etc
            if (type) {
                self._client.addMember(sourceId, targetId, type);
            }
        };

        this._setMetaConnectionType(SET_VALIDCHILDREN);

        //add extra visual piece
        $btnGroupConnectionType = this.designerCanvas.addRadioButtonGroup(function (event, data) {
            self._setMetaConnectionType(data.mode);
        });

        this.designerCanvas.addButton({ "title": SET_VALIDCHILDREN,
            "icon": "icon-meta-containment",
            "selected": true,
            "data": { "mode": SET_VALIDCHILDREN }}, $btnGroupConnectionType );

        this.designerCanvas.addButton({ "title": SET_VALIDINHERITOR,
            "icon": "icon-meta-inheritance",
            "data": { "mode": SET_VALIDINHERITOR }}, $btnGroupConnectionType );

        this.designerCanvas.addButton({ "title": SET_VALIDSOURCE,
            "icon": "icon-meta-set_validsource",
            "data": { "mode": SET_VALIDSOURCE }}, $btnGroupConnectionType );

        this.designerCanvas.addButton({ "title": SET_VALIDDESTINATION,
            "icon": "icon-meta-set_validdestination",
            "data": { "mode": SET_VALIDDESTINATION }}, $btnGroupConnectionType );

        this.designerCanvas.addButton({ "title": SET_GENERAL,
            "icon": "icon-meta-set_general",
            "data": { "mode": SET_GENERAL }}, $btnGroupConnectionType );

        //in DEBUG mode add additional content to canvas
        if (DEBUG) {
            //this._addMetaDebugModeExtensions();
        }

        this.logger.debug("MetaDesignerControl ctor");
    };

    _.extend(MetaDesignerControl.prototype, __parent_proto__);
    //in DEBUG mode add additional extensions
    if (DEBUG) {
        _.extend(MetaDesignerControl.prototype, MetaDesignerControlDEBUG.prototype);
    }

    /************** OVERRIDE ************************/
    MetaDesignerControl.prototype._getObjectDescriptor = function (nodeId) {
        var nodeObj = this._client.getNode(nodeId),
            objDescriptor,
            pos;

        if (nodeObj) {
            objDescriptor = {};

            objDescriptor.id = nodeObj.getId();
            objDescriptor.parentId = nodeObj.getParentId();

            pos = nodeObj.getRegistry(nodePropertyNames.Registry.position) || { "x": 100, "y": 100 };

            objDescriptor.position = { "x": pos.x, "y": pos.y};

            if (objDescriptor.position.hasOwnProperty("x")) {
                objDescriptor.position.x = this._getDefaultValueForNumber(objDescriptor.position.x, 0);
            } else {
                objDescriptor.position.x = 0;
            }

            if (objDescriptor.position.hasOwnProperty("y")) {
                objDescriptor.position.y = this._getDefaultValueForNumber(objDescriptor.position.y, 0);
            } else {
                objDescriptor.position.y = 0;
            }

            objDescriptor.decorator = "DefaultDecorator";
        }

        return objDescriptor;
    };

    MetaDesignerControl.prototype._dispatchEvents = function (events) {
        var i = events.length,
            e;

        this.logger.debug("_dispatchEvents '" + i + "' items");

        this.designerCanvas.beginUpdate();

        this.delayedEvents = [];

        this.firstRun = true;

        while (i--) {
            e = events[i];
            switch (e.etype) {
                case LOAD_EVENT_NAME:
                    this._onLoad(e.eid, e.desc);
                    break;
                case "update":
                    this._onUpdate(e.eid, e.desc);
                    break;
                case "unload":
                    this._onUnload(e.eid);
                    break;
            }
        }

        this.firstRun = false;

        i = events.length;

        while (i--) {
            e = events[i];
            switch (e.etype) {
                case LOAD_EVENT_NAME:
                    this._onLoad(e.eid, e.desc);
                    break;
            }
        }

        this.delayedEvents = [];

        this.designerCanvas.endUpdate();

        this.logger.debug("_dispatchEvents '" + events.length + "' items - DONE");

        //continue processing event queue
        this.processNextInQueue();
    };

        // PUBLIC METHODS
    MetaDesignerControl.prototype._onLoad = function (gmeID, objD) {
        var obj,
            objDesc,
            setMemberIds,
            decClass,
            i,
            uiComponent,
            sets = [SET_VALIDINHERITOR, SET_VALIDCHILDREN, SET_VALIDDESTINATION, SET_VALIDSOURCE, SET_GENERAL],
            setlen = sets.length;

        //component loaded
        //we are interested in the load of subcomponents of the opened component
        if (this.currentNodeInfo.id !== gmeID) {
            if (objD) {

                objDesc = _.extend({}, objD);

                if (this.firstRun === false) {
                    var nodeObj = this._client.getNode(gmeID);

                    while (setlen--) {
                        setMemberIds = nodeObj.getMemberIds(sets[setlen]);
                        if (setMemberIds) {

                            objDesc = {};

                            objDesc.srcObjId = this._GmeID2ComponentID[gmeID][0];
                            objDesc.srcSubCompId = undefined;
                            objDesc.reconnectable = false;

                            _.extend(objDesc, this._getModeVisualDescriptor(sets[setlen]));

                            i = setMemberIds.length;
                            while (i--) {
                                if (this._GmeID2ComponentID.hasOwnProperty(setMemberIds[i]) &&
                                    this._GmeID2ComponentID[setMemberIds[i]].length > 0) {
                                    objDesc.dstObjId = this._GmeID2ComponentID[setMemberIds[i]][0];
                                    objDesc.dstSubCompId = undefined;
                                    obj = this.designerCanvas.createConnection(objDesc);

                                    this._setRelations[obj.id] = { "owner": gmeID,
                                                                   "member": setMemberIds[i],
                                                                   "set": sets[setlen] };
                                }
                            }
                        }
                    }
                } else {
                    this._GmeID2ComponentID[gmeID] = [];
                    this._GMEModels.push(gmeID);

                    decClass = this.decoratorClasses[objDesc.decorator];

                    objDesc.decoratorClass = decClass;
                    objDesc.control = this;
                    objDesc.metaInfo = {"GMEID" : gmeID};

                    uiComponent = this.designerCanvas.createDesignerItem(objDesc);

                    this._GmeID2ComponentID[gmeID].push(uiComponent.id);
                    this._ComponentID2GmeID[uiComponent.id] = gmeID;
                }
            }
        }
    };

    MetaDesignerControl.prototype._setMetaConnectionType = function (mode) {
        var params = {},
            metaInfo = {};

        if (this._connectionType !== mode) {
            metaInfo = {"type": mode };
            this.designerCanvas.connectionDrawingManager.setMetaInfo(metaInfo);

            params = this._getModeVisualDescriptor(mode);

            this.designerCanvas.connectionDrawingManager.setConnectionInDrawProperties(params);
        }
    };

    MetaDesignerControl.prototype._getModeVisualDescriptor = function (mode) {
        var params = { "arrowStart" : "none",
                        "arrowEnd" : "none",
                        "width" : "1",
                        "color" :"#AAAAAA" };

        switch (mode) {
            case SET_VALIDCHILDREN:
                params.arrowStart = VALIDCHILDREN_TYPE_LINE_END;
                params.arrowEnd = NOEND;
                params.width = "5";
                params.color = "#FF0000";
                break;
            case SET_VALIDINHERITOR:
                params.arrowStart = VALIDINHERITOR_TYPE_LINE_END;
                params.arrowEnd = NOEND;
                params.width = "3";
                params.color = "#0000FF";
                break;
            case SET_VALIDSOURCE:
                params.arrowStart = VALIDSOURCE_TYPE_LINE_END;
                params.arrowEnd = NOEND;
                params.width = "3";
                params.color = "#00FF00";
                break;
            case SET_VALIDDESTINATION:
                params.arrowStart = NOEND;
                params.arrowEnd = VALIDDESTINATION_TYPE_LINE_END
                params.width = "3";
                params.color = "#AA03C3";
                break;
            case SET_GENERAL:
                params.arrowStart = GENERAL_TYPE_LINE_END;
                params.arrowEnd = NOEND;
                params.width = "2";
                params.color = "#000000";
                break;
            default:
                break;
        }

        return params;
    };

    return MetaDesignerControl;
});<commit_msg>filter out grandchlidrens<commit_after>"use strict";

define(['logManager',
    'clientUtil',
    'commonUtil',
    'js/ModelEditor3/DesignerControl',
    'js/DiagramDesigner/NodePropertyNames',
    'js/ModelEditor3/MetaDesignerControl.DEBUG',
    'css!ModelEditor3CSS/MetaDesignerControl'], function (logManager,
                                                     clientUtil,
                                                     commonUtil,
                                                     DesignerControl,
                                                     nodePropertyNames,
                                                     MetaDesignerControlDEBUG) {

    var MetaDesignerControl,
        __parent__ = DesignerControl,
        __parent_proto__ = DesignerControl.prototype,
        VALIDCHILDREN_TYPE_LINE_END = "diamond-wide-long",
        VALIDINHERITOR_TYPE_LINE_END = "block-wide-long",
        VALIDSOURCE_TYPE_LINE_END = "oval-wide-long",
        VALIDDESTINATION_TYPE_LINE_END = "open-wide-long",
        GENERAL_TYPE_LINE_END = "none",
        NOEND = "none",
        LOAD_EVENT_NAME = "load",
        SET_VALIDCHILDREN = 'ValidChildren',
        SET_VALIDSOURCE = 'ValidSource',
        SET_VALIDDESTINATION = 'ValidDestination',
        SET_VALIDINHERITOR = 'ValidInheritor',
        SET_GENERAL = 'General';

    MetaDesignerControl = function (options) {
        var self = this,
            $btnGroupConnectionType;

        options.loggerName = options.loggerName || "MetaDesignerControl";

        //execute parent's constructor
        __parent__.apply(this, [options]);

        this._setRelations = {};

        //override parent's event handlers
        this.designerCanvas.onSelectionDelete = function (idList) {
            var len = idList.length,
                desc;

            while (len--) {
                if (self._setRelations[idList[len]]) {
                    desc = self._setRelations[idList[len]];
                    self._client.removeMember(desc.owner, desc.member, desc.set);
                    delete self._setRelations[idList[len]];
                    self.designerCanvas.deleteComponent(idList[len]);

                }
            }
        };

        this.designerCanvas.onCreateNewConnection = function (params) {
            var type = params.metaInfo.type,
                sourceId = self._ComponentID2GmeID[params.src],
                targetId = self._ComponentID2GmeID[params.dst];

            //connDesc.type has special meaning: inheritance, containment, etc
            if (type) {
                self._client.addMember(sourceId, targetId, type);
            }
        };

        this._setMetaConnectionType(SET_VALIDCHILDREN);

        //add extra visual piece
        $btnGroupConnectionType = this.designerCanvas.addRadioButtonGroup(function (event, data) {
            self._setMetaConnectionType(data.mode);
        });

        this.designerCanvas.addButton({ "title": SET_VALIDCHILDREN,
            "icon": "icon-meta-containment",
            "selected": true,
            "data": { "mode": SET_VALIDCHILDREN }}, $btnGroupConnectionType );

        this.designerCanvas.addButton({ "title": SET_VALIDINHERITOR,
            "icon": "icon-meta-inheritance",
            "data": { "mode": SET_VALIDINHERITOR }}, $btnGroupConnectionType );

        this.designerCanvas.addButton({ "title": SET_VALIDSOURCE,
            "icon": "icon-meta-set_validsource",
            "data": { "mode": SET_VALIDSOURCE }}, $btnGroupConnectionType );

        this.designerCanvas.addButton({ "title": SET_VALIDDESTINATION,
            "icon": "icon-meta-set_validdestination",
            "data": { "mode": SET_VALIDDESTINATION }}, $btnGroupConnectionType );

        this.designerCanvas.addButton({ "title": SET_GENERAL,
            "icon": "icon-meta-set_general",
            "data": { "mode": SET_GENERAL }}, $btnGroupConnectionType );

        //in DEBUG mode add additional content to canvas
        if (DEBUG) {
            //this._addMetaDebugModeExtensions();
        }

        this.logger.debug("MetaDesignerControl ctor");
    };

    _.extend(MetaDesignerControl.prototype, __parent_proto__);
    //in DEBUG mode add additional extensions
    if (DEBUG) {
        _.extend(MetaDesignerControl.prototype, MetaDesignerControlDEBUG.prototype);
    }

    /************** OVERRIDE ************************/
    MetaDesignerControl.prototype._getObjectDescriptor = function (nodeId) {
        var nodeObj = this._client.getNode(nodeId),
            objDescriptor,
            pos;

        if (nodeObj) {
            objDescriptor = {};

            objDescriptor.id = nodeObj.getId();
            objDescriptor.parentId = nodeObj.getParentId();

            pos = nodeObj.getRegistry(nodePropertyNames.Registry.position) || { "x": 100, "y": 100 };

            objDescriptor.position = { "x": pos.x, "y": pos.y};

            if (objDescriptor.position.hasOwnProperty("x")) {
                objDescriptor.position.x = this._getDefaultValueForNumber(objDescriptor.position.x, 0);
            } else {
                objDescriptor.position.x = 0;
            }

            if (objDescriptor.position.hasOwnProperty("y")) {
                objDescriptor.position.y = this._getDefaultValueForNumber(objDescriptor.position.y, 0);
            } else {
                objDescriptor.position.y = 0;
            }

            objDescriptor.decorator = "DefaultDecorator";
        }

        return objDescriptor;
    };

    MetaDesignerControl.prototype._dispatchEvents = function (events) {
        var i = events.length,
            e;

        this.logger.debug("_dispatchEvents '" + i + "' items");

        this.designerCanvas.beginUpdate();

        this.delayedEvents = [];

        this.firstRun = true;

        while (i--) {
            e = events[i];
            switch (e.etype) {
                case LOAD_EVENT_NAME:
                    this._onLoad(e.eid, e.desc);
                    break;
                case "update":
                    this._onUpdate(e.eid, e.desc);
                    break;
                case "unload":
                    this._onUnload(e.eid);
                    break;
            }
        }

        this.firstRun = false;

        i = events.length;

        while (i--) {
            e = events[i];
            switch (e.etype) {
                case LOAD_EVENT_NAME:
                    this._onLoad(e.eid, e.desc);
                    break;
            }
        }

        this.delayedEvents = [];

        this.designerCanvas.endUpdate();

        this.logger.debug("_dispatchEvents '" + events.length + "' items - DONE");

        //continue processing event queue
        this.processNextInQueue();
    };

        // PUBLIC METHODS
    MetaDesignerControl.prototype._onLoad = function (gmeID, objD) {
        var obj,
            objDesc,
            setMemberIds,
            decClass,
            i,
            uiComponent,
            sets = [SET_VALIDINHERITOR, SET_VALIDCHILDREN, SET_VALIDDESTINATION, SET_VALIDSOURCE, SET_GENERAL],
            setlen = sets.length;

        //component loaded
        //we are interested in the load of subcomponents of the opened component
        if (this.currentNodeInfo.id !== gmeID) {
            if (objD && this.currentNodeInfo.id === objD.parentId) {

                objDesc = _.extend({}, objD);

                if (this.firstRun === false) {
                    var nodeObj = this._client.getNode(gmeID);

                    while (setlen--) {
                        setMemberIds = nodeObj.getMemberIds(sets[setlen]);
                        if (setMemberIds) {

                            objDesc = {};

                            objDesc.srcObjId = this._GmeID2ComponentID[gmeID][0];
                            objDesc.srcSubCompId = undefined;
                            objDesc.reconnectable = false;

                            _.extend(objDesc, this._getModeVisualDescriptor(sets[setlen]));

                            i = setMemberIds.length;
                            while (i--) {
                                if (this._GmeID2ComponentID.hasOwnProperty(setMemberIds[i]) &&
                                    this._GmeID2ComponentID[setMemberIds[i]].length > 0) {
                                    objDesc.dstObjId = this._GmeID2ComponentID[setMemberIds[i]][0];
                                    objDesc.dstSubCompId = undefined;
                                    obj = this.designerCanvas.createConnection(objDesc);

                                    this._setRelations[obj.id] = { "owner": gmeID,
                                                                   "member": setMemberIds[i],
                                                                   "set": sets[setlen] };
                                }
                            }
                        }
                    }
                } else {
                    this._GmeID2ComponentID[gmeID] = [];
                    this._GMEModels.push(gmeID);

                    decClass = this.decoratorClasses[objDesc.decorator];

                    objDesc.decoratorClass = decClass;
                    objDesc.control = this;
                    objDesc.metaInfo = {"GMEID" : gmeID};

                    uiComponent = this.designerCanvas.createDesignerItem(objDesc);

                    this._GmeID2ComponentID[gmeID].push(uiComponent.id);
                    this._ComponentID2GmeID[uiComponent.id] = gmeID;
                }
            }
        }
    };

    MetaDesignerControl.prototype._setMetaConnectionType = function (mode) {
        var params = {},
            metaInfo = {};

        if (this._connectionType !== mode) {
            metaInfo = {"type": mode };
            this.designerCanvas.connectionDrawingManager.setMetaInfo(metaInfo);

            params = this._getModeVisualDescriptor(mode);

            this.designerCanvas.connectionDrawingManager.setConnectionInDrawProperties(params);
        }
    };

    MetaDesignerControl.prototype._getModeVisualDescriptor = function (mode) {
        var params = { "arrowStart" : "none",
                        "arrowEnd" : "none",
                        "width" : "1",
                        "color" :"#AAAAAA" };

        switch (mode) {
            case SET_VALIDCHILDREN:
                params.arrowStart = VALIDCHILDREN_TYPE_LINE_END;
                params.arrowEnd = NOEND;
                params.width = "5";
                params.color = "#FF0000";
                break;
            case SET_VALIDINHERITOR:
                params.arrowStart = VALIDINHERITOR_TYPE_LINE_END;
                params.arrowEnd = NOEND;
                params.width = "3";
                params.color = "#0000FF";
                break;
            case SET_VALIDSOURCE:
                params.arrowStart = VALIDSOURCE_TYPE_LINE_END;
                params.arrowEnd = NOEND;
                params.width = "3";
                params.color = "#00FF00";
                break;
            case SET_VALIDDESTINATION:
                params.arrowStart = NOEND;
                params.arrowEnd = VALIDDESTINATION_TYPE_LINE_END
                params.width = "3";
                params.color = "#AA03C3";
                break;
            case SET_GENERAL:
                params.arrowStart = GENERAL_TYPE_LINE_END;
                params.arrowEnd = NOEND;
                params.width = "2";
                params.color = "#000000";
                break;
            default:
                break;
        }

        return params;
    };

    return MetaDesignerControl;
});<|endoftext|>


<commit_before>const rethink = require('rethinkdb');
const helperFunctions = require('../../auth-helpers');
const pipelineChangedSubsPreprocess = require('./pipelineChanged');
const userMetadataChangedSubsPreprocess = require('./userMetadataChanged');

// Add new tables here to create a new changefeed on server start
const tables = [
  { tableName: 'computations', idVar: 'computationId', subVar: 'computationChanged' },
  { tableName: 'consortia', idVar: 'consortiumId', subVar: 'consortiumChanged' },
  { tableName: 'pipelines', idVar: 'pipelineId', subVar: 'pipelineChanged', preprocess: pipelineChangedSubsPreprocess },
  { tableName: 'users', idVar: 'userId', subVar: 'userChanged' },
  { tableName: 'users', idVar: 'userId', subVar: 'userMetadataChanged', preprocess: userMetadataChangedSubsPreprocess },
  { tableName: 'runs', idVar: 'runId', subVar: 'userRunChanged' },
];

/**
 * Initialize RethinkDB changefeeds to detect table changes and fire off GraphQL subscription topics
 * @param {object} pubsub GraphQL publish and subscribe object
 */
const initSubscriptions = (pubsub) => {
  tables.forEach((table) => {
    helperFunctions.getRethinkConnection()
      .then(connection => rethink.table(table.tableName).changes().run(connection))
      .then(feed => feed.each((err, change) => {
        let val = {};

        if (!change.new_val) {
          val = Object.assign({}, change.old_val, { delete: true });
        } else {
          val = change.new_val;
        }

        const preprocessPromise = table.preprocess ? table.preprocess(val) : Promise.resolve(val);

        preprocessPromise
          .then(result =>
            pubsub.publish(table.subVar, {
              [table.subVar]: result,
              [table.idVar]: result.id,
            })
          )
      }))
  });
};

module.exports = initSubscriptions;
<commit_msg>add logging to gql sub<commit_after>const rethink = require('rethinkdb');
const helperFunctions = require('../../auth-helpers');
const pipelineChangedSubsPreprocess = require('./pipelineChanged');
const userMetadataChangedSubsPreprocess = require('./userMetadataChanged');

// Add new tables here to create a new changefeed on server start
const tables = [
  { tableName: 'computations', idVar: 'computationId', subVar: 'computationChanged' },
  { tableName: 'consortia', idVar: 'consortiumId', subVar: 'consortiumChanged' },
  {
    tableName: 'pipelines', idVar: 'pipelineId', subVar: 'pipelineChanged', preprocess: pipelineChangedSubsPreprocess,
  },
  { tableName: 'users', idVar: 'userId', subVar: 'userChanged' },
  {
    tableName: 'users', idVar: 'userId', subVar: 'userMetadataChanged', preprocess: userMetadataChangedSubsPreprocess,
  },
  { tableName: 'runs', idVar: 'runId', subVar: 'userRunChanged' },
];

/**
 * Initialize RethinkDB changefeeds to detect table changes and fire off GraphQL subscription topics
 * @param {object} pubsub GraphQL publish and subscribe object
 */
const initSubscriptions = (pubsub) => {
  tables.forEach((table) => {
    helperFunctions.getRethinkConnection()
      .then(connection => rethink.table(table.tableName).changes().run(connection))
      .then(feed => feed.each((err, change) => {
        console.log(`GraphQL changefeed error: ${err}`);
        let val = {};

        if (!change.new_val) {
          val = Object.assign({}, change.old_val, { delete: true });
        } else {
          val = change.new_val;
        }

        const preprocessPromise = table.preprocess ? table.preprocess(val) : Promise.resolve(val);

        preprocessPromise
          .then(result => pubsub.publish(table.subVar, {
            [table.subVar]: result,
            [table.idVar]: result.id,
          }));
      }));
  });
};

module.exports = initSubscriptions;
<|endoftext|>


<commit_before>// Write your package code here!

// The scaffolding command.
ScaffoldingCommand = {};

// Sets the command name.
ScaffoldingCommand.name = "scaffolding";

// Sets the command summary.
ScaffoldingCommand.summary = "A collection of temporary commands implemented for testing purposes.";

// Sets the command text.
ScaffoldingCommand.text = "The scaffolding command is just a collection of unrelated commands that will used for testing and removed as their replacements are developed.
"
  + "For example, say that I want to implement a broadcasting functionality that will allow an admin to broadcast a message to all connected users.  I can implement the broad strokes under scaffolding, see that it works, and then implement a more final version in its own package.
"
  + "This should make it easier to develop complicated functionality, since I can get a quick-and-dirty form implemented and then develop each component in a secure and reliable form once the proof-of-concept has been shown to work.
";

// Sets the command categories.
ScaffoldingCommand.categories = ["Commands", "OOC Commands"];

// Sets the command search terms.
ScaffoldingCommand.searchTerms = ["scaffolding", "temporary", "wizard", "admin"];

// Sets the command permsissions.
ScaffoldingCommand.permissions = ["nathan"];

// Sets the command type.
ScaffoldingCommand.type = ["Developer"];

/**
 * Handle the command.
 *
 * @param {[string]} arguments - The arguments supplied to the command.
 * @param {function} completionHandler - A completion handler that takes an
 * object.
 */

ScaffoldingCommand.handler = function (arguments, completionHandler) {

  // Fail catastrophically if we're passed an arguments object that isn't an array.
  if (!MeteorMUD.Underscore.isArray(arguments)) {
    throw new Error("Arguments is not an array.");
  }

  // "Scaffolding" by itself isn't a valid command, so let's check the subcommands.
  var subcommands = ScaffoldingCommand.subcommands;

  // Catch the case where we don't have any subcommands.
  if (!subcommands || subcommands.length === 0) {
    return MeteorMUD.complete(completionHandler, {
      success: false,
      error: {
        message: "Could not execute '" + ScaffoldingCommand.name + "' command.",
        reason:  "'" + ScaffoldingCommand.name + "'  is not fully implemented; wait until there are subcommands!",
      },
    });
  }

  // Otherwise, list the valid subcommands.
  // Should shift this to some functionality of Commands.
  return MeteorMUD.complete(completionHandler, {
    success: false,
    error: {
      message: "Could not execute '" + ScaffoldingCommand.name + "' command because you didn't specify a valid subcommand.",
      reason: "Valid subcommands for '" + ScaffoldingCommand.name + "' are " + MeteorMUD.UnderscoreString.toSentenceSerial(subcommands) + "."
    },
  });
};

// The "yell" scaffolding command.
YellCommand = {};

// Sets the command name.
YellCommand.name = "scaffolding-yell";

// Sets the command summary.
YellCommand.summary = ScaffoldingCommand.summary;

// Sets the command text.
YellCommand.text = ScaffoldingCommand.text;

// Sets the command categories.
YellCommand.categories = ScaffoldingCommand.categories;

// Sets the command search terms.
YellCommand.searchTerms = ScaffoldingCommand.searchTerms;

// Sets the command permsissions.
YellCommand.permissions = ScaffoldingCommand.permissions;

// Sets the command type.
YellCommand.type = ScaffoldingCommand.type;

/**
 * Handle the command.
 *
 * @param {[string]} arguments - The arguments supplied to the command.
 * @param {function} completionHandler - A completion handler that takes an
 * object.
 */

YellCommand.handler = function (arguments, completionHandler) {
  console.log(arguments);

  // Fail catastrophically if we're passed an arguments object that isn't an array.
  if (!MeteorMUD.Underscore.isArray(arguments)) {
    throw new Error("Arguments is not an array.");
  }

  var message = "" + Meteor.user().username + " yells: " + arguments.join(" ");
  var cleanedMessage = MeteorMUD.Schemas.Message.clean({
    message: message,
  });
  UserStatus.connections.find({}).fetch().forEach(function (connection) {
    MeteorMUD.Output.sendOutput(connection._id, cleanedMessage);
  });

  // Otherwise, list the valid subcommands.
  // Should shift this to some functionality of Commands.
  return MeteorMUD.complete(completionHandler, {
    success: true,
    message: "Yelled '" + arguments.join(" ") + "'.",
  });
};

Meteor.startup(function () {
  // Startup code goes here.

  // Clean the command.
  Schemas.Command.clean(ScaffoldingCommand);

  // Add the scaffolding command.
  MeteorMUD.Commands.addCommand(ScaffoldingCommand);

  // Clean the command.
  Schemas.Command.clean(YellCommand);

  // Add the yell command.
  MeteorMUD.Commands.addCommand(YellCommand);

  // Add the yell subcommand.
  MeteorMUD.Commands.addSubcommand("scaffolding", "yell");
});

<commit_msg>Adds scaffolding-tell command.<commit_after>// Write your package code here!

// The scaffolding command.
ScaffoldingCommand = {};

// Sets the command name.
ScaffoldingCommand.name = "scaffolding";

// Sets the command summary.
ScaffoldingCommand.summary = "A collection of temporary commands implemented for testing purposes.";

// Sets the command text.
ScaffoldingCommand.text = "The scaffolding command is just a collection of unrelated commands that will used for testing and removed as their replacements are developed.
"
  + "For example, say that I want to implement a broadcasting functionality that will allow an admin to broadcast a message to all connected users.  I can implement the broad strokes under scaffolding, see that it works, and then implement a more final version in its own package.
"
  + "This should make it easier to develop complicated functionality, since I can get a quick-and-dirty form implemented and then develop each component in a secure and reliable form once the proof-of-concept has been shown to work.
";

// Sets the command categories.
ScaffoldingCommand.categories = ["Commands", "OOC Commands"];

// Sets the command search terms.
ScaffoldingCommand.searchTerms = ["scaffolding", "temporary", "wizard", "admin"];

// Sets the command permsissions.
ScaffoldingCommand.permissions = ["nathan"];

// Sets the command type.
ScaffoldingCommand.type = ["Developer"];

/**
 * Handle the command.
 *
 * @param {[string]} arguments - The arguments supplied to the command.
 * @param {function} completionHandler - A completion handler that takes an
 * object.
 */

ScaffoldingCommand.handler = function (arguments, completionHandler) {

  // Fail catastrophically if we're passed an arguments object that isn't an array.
  if (!MeteorMUD.Underscore.isArray(arguments)) {
    throw new Error("Arguments is not an array.");
  }

  // "Scaffolding" by itself isn't a valid command, so let's check the subcommands.
  var subcommands = ScaffoldingCommand.subcommands;

  // Catch the case where we don't have any subcommands.
  if (!subcommands || subcommands.length === 0) {
    return MeteorMUD.complete(completionHandler, {
      success: false,
      error: {
        message: "Could not execute '" + ScaffoldingCommand.name + "' command.",
        reason:  "'" + ScaffoldingCommand.name + "'  is not fully implemented; wait until there are subcommands!",
      },
    });
  }

  // Otherwise, list the valid subcommands.
  // Should shift this to some functionality of Commands.
  return MeteorMUD.complete(completionHandler, {
    success: false,
    error: {
      message: "Could not execute '" + ScaffoldingCommand.name + "' command because you didn't specify a valid subcommand.",
      reason: "Valid subcommands for '" + ScaffoldingCommand.name + "' are " + MeteorMUD.UnderscoreString.toSentenceSerial(subcommands) + "."
    },
  });
};

// The "yell" scaffolding command.
YellCommand = {};

// Sets the command name.
YellCommand.name = "scaffolding-yell";

// Sets the command summary.
YellCommand.summary = ScaffoldingCommand.summary;

// Sets the command text.
YellCommand.text = ScaffoldingCommand.text;

// Sets the command categories.
YellCommand.categories = ScaffoldingCommand.categories;

// Sets the command search terms.
YellCommand.searchTerms = ScaffoldingCommand.searchTerms;

// Sets the command permsissions.
YellCommand.permissions = ScaffoldingCommand.permissions;

// Sets the command type.
YellCommand.type = ScaffoldingCommand.type;

/**
 * Handle the command.
 *
 * @param {[string]} arguments - The arguments supplied to the command.
 * @param {function} completionHandler - A completion handler that takes an
 * object.
 */

YellCommand.handler = function (arguments, completionHandler) {

  // Fail catastrophically if we're passed an arguments object that isn't an array.
  if (!MeteorMUD.Underscore.isArray(arguments)) {
    throw new Error("Arguments is not an array.");
  }

  var message = "" + Meteor.user().username + " yells: " + arguments.join(" ");
  var cleanedMessage = MeteorMUD.Schemas.Message.clean({
    message: message,
  });
  UserStatus.connections.find({}).fetch().forEach(function (connection) {
    MeteorMUD.Output.sendOutput(connection._id, cleanedMessage);
  });

  // Otherwise, list the valid subcommands.
  // Should shift this to some functionality of Commands.
  return MeteorMUD.complete(completionHandler, {
    success: true,
    message: "Yelled '" + arguments.join(" ") + "'.",
  });
};

// The "tell" scaffolding command.
TellCommand = {};

// Sets the command name.
TellCommand.name = "scaffolding-tell";

// Sets the command summary.
TellCommand.summary = ScaffoldingCommand.summary;

// Sets the command text.
TellCommand.text = ScaffoldingCommand.text;

// Sets the command categories.
TellCommand.categories = ScaffoldingCommand.categories;

// Sets the command search terms.
TellCommand.searchTerms = ScaffoldingCommand.searchTerms;

// Sets the command permsissions.
TellCommand.permissions = ScaffoldingCommand.permissions;

// Sets the command type.
TellCommand.type = ScaffoldingCommand.type;

/**
 * Handle the command.
 *
 * @param {[string]} arguments - The arguments supplied to the command.
 * @param {function} completionHandler - A completion handler that takes an
 * object.
 */

TellCommand.handler = function (arguments, completionHandler) {

  // Fail catastrophically if we're passed an arguments object that isn't an array.
  if (!MeteorMUD.Underscore.isArray(arguments)) {
    throw new Error("Arguments is not an array.");
  }

  var message = "" + Meteor.user().username + " tells you: " + arguments.slice(1).join(" ");
  var cleanedMessage = MeteorMUD.Schemas.Message.clean({
    message: message,
  });
  var userId = Meteor.users.findOne({ username: arguments[0] })._id;
  UserStatus.connections.find({ userId: userId }).fetch().forEach(function (connection) {
    MeteorMUD.Output.sendOutput(connection._id, cleanedMessage);
  });

  // Otherwise, list the valid subcommands.
  // Should shift this to some functionality of Commands.
  return MeteorMUD.complete(completionHandler, {
    success: true,
    message: "Told " + arguments[0] + " '" + arguments.slice(1).join(" ") + "'.",
  });
};

Meteor.startup(function () {
  // Startup code goes here.

  // Clean the command.
  Schemas.Command.clean(ScaffoldingCommand);

  // Add the scaffolding command.
  MeteorMUD.Commands.addCommand(ScaffoldingCommand);

  // Clean the command.
  Schemas.Command.clean(YellCommand);

  // Add the yell command.
  MeteorMUD.Commands.addCommand(YellCommand);

  // Add the yell subcommand.
  MeteorMUD.Commands.addSubcommand("scaffolding", "yell");

  // Clean the command.
  Schemas.Command.clean(TellCommand);

  // Add the yell command.
  MeteorMUD.Commands.addCommand(TellCommand);

  // Add the yell subcommand.
  MeteorMUD.Commands.addSubcommand("scaffolding", "tell");
});

<|endoftext|>


<commit_before>module.exports = {
	rules: {
		'type-enum': [2,
			'always',
			[
				'feat',
				'fix',
				'docs',
				'style',
				'refactor',
				'test',
				'chore',
				'revert'
			]
		],
		'type-case': [2,
			'always',
			'lowerCase'
		],
		'type-empty': [2,
			'never'
		],
		'type-max-length': [0,
			'always',
			'Infinity'
		],
		'type-min-length': [0,
			'always',
			0
		],
		'scope-enum': [0,
			'always',
			[]
		],
		'scope-case': [2,
			'always',
			'lowerCase'
		],
		'scope-empty': [0,
			'never'
		],
		'scope-max-length': [0,
			'always',
			'Infinity'
		],
		'scope-min-length': [0,
			'always',
			0],
		'subject-case': [0,
			'always',
			'lowerCase'
		],
		'subject-empty': [2,
			'never'
		],
		'subject-max-length': [0,
			'always',
			'Infinity'
		],
		'subject-min-length': [0,
			'always',
			0
		],
		'subject-full-stop': [2,
			'never',
			'.'
		],
		'body-case': [2,
			'always',
			'lowerCase'
		],
		'body-empty': [0,
			'never'
		],
		'body-leading-blank': [1,
			'always'
		],
		'body-max-length': [0,
			'always',
			'Infinity'
		],
		'body-min-length': [0,
			'always',
			0
		],
		'header-max-length': [2,
			'always',
			80
		],
		'header-min-length': [0,
			'always',
			0
		],
		'lang': [1,
			'always',
			'en'
		]
	},
	wildcards: {
		merge: [
			'/^(Merge pull request)|(Merge (.*?) into (.*?)$)/'
		],
		release: [
			'/^\\d.\\d.\\d$/'
		],
		revert: [
			'revert: (.*)'
		]
	}
};
<commit_msg>style: fix indentation<commit_after>module.exports = {
	rules: {
		'type-enum': [2,
			'always',
			[
				'feat',
				'fix',
				'docs',
				'style',
				'refactor',
				'test',
				'chore',
				'revert'
			]
		],
		'type-case': [2,
			'always',
			'lowerCase'
		],
		'type-empty': [2,
			'never'
		],
		'type-max-length': [0,
			'always',
			'Infinity'
		],
		'type-min-length': [0,
			'always',
			0
		],
		'scope-enum': [0,
			'always',
			[]
		],
		'scope-case': [2,
			'always',
			'lowerCase'
		],
		'scope-empty': [0,
			'never'
		],
		'scope-max-length': [0,
			'always',
			'Infinity'
		],
		'scope-min-length': [0,
			'always',
			0
		],
		'subject-case': [0,
			'always',
			'lowerCase'
		],
		'subject-empty': [2,
			'never'
		],
		'subject-max-length': [0,
			'always',
			'Infinity'
		],
		'subject-min-length': [0,
			'always',
			0
		],
		'subject-full-stop': [2,
			'never',
			'.'
		],
		'body-case': [2,
			'always',
			'lowerCase'
		],
		'body-empty': [0,
			'never'
		],
		'body-leading-blank': [1,
			'always'
		],
		'body-max-length': [0,
			'always',
			'Infinity'
		],
		'body-min-length': [0,
			'always',
			0
		],
		'header-max-length': [2,
			'always',
			80
		],
		'header-min-length': [0,
			'always',
			0
		],
		'lang': [1,
			'always',
			'en'
		]
	},
	wildcards: {
		merge: [
			'/^(Merge pull request)|(Merge (.*?) into (.*?)$)/'
		],
		release: [
			'/^\\d.\\d.\\d$/'
		],
		revert: [
			'revert: (.*)'
		]
	}
};
<|endoftext|>


<commit_before>import React, { useEffect } from 'react';
import { useIntl } from 'react-intl';
import { useQuery } from 'react-query';
import styled from 'styled-components';
import { Helmet } from 'react-helmet';
import {
  pxToRem,
  CheckPagePermissions,
  useTracking,
  LoadingIndicatorPage,
  useNotification,
} from '@strapi/helper-plugin';
import { useNotifyAT } from '@strapi/design-system/LiveRegions';
import { Layout, HeaderLayout, ContentLayout } from '@strapi/design-system/Layout';
import { Flex } from '@strapi/design-system/Flex';
import { Box } from '@strapi/design-system/Box';
import { Stack } from '@strapi/design-system/Stack';
import { LinkButton } from '@strapi/design-system/LinkButton';
import { Main } from '@strapi/design-system/Main';
import { Typography } from '@strapi/design-system/Typography';
import { fetchPlugins } from './utils/api';
import adminPermissions from '../../permissions';
import MarketplacePicture from './assets/marketplace-coming-soon.png';

const CenterTypography = styled(Typography)`
  text-align: center;
`;

const Img = styled.img`
  width: ${190 / 16}rem;
`;

const StackCentered = styled(Stack)`
  align-items: center;
`;

const MarketPlacePage = () => {
  const { formatMessage } = useIntl();
  const { trackUsage } = useTracking();
  const toggleNotification = useNotification();
  const { notifyStatus } = useNotifyAT();

  const notifyLoad = () => {
    notifyStatus(
      formatMessage(
        {
          id: 'app.utils.notify.data-loaded',
          defaultMessage: 'The {target} has loaded',
        },
        { target: 'test' }
      )
    );
  };

  const { status, data } = useQuery('list-plugins', () => fetchPlugins(notifyLoad), {
    onError: () => {
      toggleNotification({
        type: 'warning',
        message: { id: 'notification.error', defaultMessage: 'An error occured' },
      });
    },
  });

  const isLoading = status !== 'success' && status !== 'error';
  console.log('plugins', data);

  useEffect(() => {
    trackUsage('didGoToMarketplace');
  }, [trackUsage]);

  if (isLoading) {
    return (
      <Layout>
        <Main aria-busy>
          <LoadingIndicatorPage />
        </Main>
      </Layout>
    );
  }

  return (
    <CheckPagePermissions permissions={adminPermissions.marketplace.main}>
      <Layout>
        <Main>
          <Helmet
            title={formatMessage({
              id: 'admin.pages.MarketPlacePage.helmet',
              defaultMessage: 'Marketplace - Plugins',
            })}
          />
          <HeaderLayout
            title={formatMessage({
              id: 'admin.pages.MarketPlacePage.title',
              defaultMessage: 'Marketplace',
            })}
            subtitle={formatMessage({
              id: 'admin.pages.MarketPlacePage.subtitle',
              defaultMessage: 'Get more out of Strapi',
            })}
          />
          <ContentLayout>
            <StackCentered
              size={0}
              hasRadius
              background="neutral0"
              shadow="tableShadow"
              paddingTop={10}
              paddingBottom={10}
            >
              <Box paddingBottom={7}>
                <Img
                  alt={formatMessage({
                    id: 'admin.pages.MarketPlacePage.illustration',
                    defaultMessage: 'marketplace illustration',
                  })}
                  src={MarketplacePicture}
                />
              </Box>
              <Typography variant="alpha">
                {formatMessage({
                  id: 'admin.pages.MarketPlacePage.coming-soon.1',
                  defaultMessage: 'A new way to make Strapi awesome.',
                })}
              </Typography>
              <Typography variant="alpha" textColor="primary700">
                {formatMessage({
                  id: 'admin.pages.MarketPlacePage.coming-soon.2',
                  defaultMessage: 'A new way to make Strapi awesome.',
                })}
              </Typography>
              <Flex maxWidth={pxToRem(580)} paddingTop={3}>
                <CenterTypography variant="epsilon" textColor="neutral600">
                  {formatMessage({
                    id: 'admin.pages.MarketPlacePage.content.subtitle',
                    defaultMessage:
                      'The new marketplace will help you get more out of Strapi. We are working hard to offer the best experience to discover and install plugins.',
                  })}
                </CenterTypography>
              </Flex>
              <Stack paddingTop={6} horizontal size={2}>
                {/* Temporarily hidden until we have the right URL for the link */}
                {/* <LinkButton href="https://strapi.io/" size="L" variant="secondary">
                  {formatMessage({
                    id: 'admin.pages.MarketPlacePage.submit.plugin.link',
                    defaultMessage: 'Submit your plugin',
                  })}
                </LinkButton> */}
                <LinkButton href="https://strapi.io/blog/strapi-market-is-coming-soon" size="L">
                  {formatMessage({
                    id: 'admin.pages.MarketPlacePage.blog.link',
                    defaultMessage: 'Read our blog post',
                  })}
                </LinkButton>
              </Stack>
            </StackCentered>
          </ContentLayout>
        </Main>
      </Layout>
    </CheckPagePermissions>
  );
};

export default MarketPlacePage;
<commit_msg>update translation<commit_after>import React, { useEffect } from 'react';
import { useIntl } from 'react-intl';
import { useQuery } from 'react-query';
import styled from 'styled-components';
import { Helmet } from 'react-helmet';
import {
  pxToRem,
  CheckPagePermissions,
  useTracking,
  LoadingIndicatorPage,
  useNotification,
} from '@strapi/helper-plugin';
import { useNotifyAT } from '@strapi/design-system/LiveRegions';
import { Layout, HeaderLayout, ContentLayout } from '@strapi/design-system/Layout';
import { Flex } from '@strapi/design-system/Flex';
import { Box } from '@strapi/design-system/Box';
import { Stack } from '@strapi/design-system/Stack';
import { LinkButton } from '@strapi/design-system/LinkButton';
import { Main } from '@strapi/design-system/Main';
import { Typography } from '@strapi/design-system/Typography';
import { fetchPlugins } from './utils/api';
import adminPermissions from '../../permissions';
import MarketplacePicture from './assets/marketplace-coming-soon.png';

const CenterTypography = styled(Typography)`
  text-align: center;
`;

const Img = styled.img`
  width: ${190 / 16}rem;
`;

const StackCentered = styled(Stack)`
  align-items: center;
`;

const MarketPlacePage = () => {
  const { formatMessage } = useIntl();
  const { trackUsage } = useTracking();
  const toggleNotification = useNotification();
  const { notifyStatus } = useNotifyAT();

  const title = formatMessage({
    id: 'admin.pages.MarketPlacePage.title',
    defaultMessage: 'Marketplace',
  });

  const notifyLoad = () => {
    notifyStatus(
      formatMessage(
        {
          id: 'app.utils.notify.data-loaded',
          defaultMessage: 'The {target} has loaded',
        },
        { target: title }
      )
    );
  };

  const { status, data } = useQuery('list-plugins', () => fetchPlugins(notifyLoad), {
    onError: () => {
      toggleNotification({
        type: 'warning',
        message: { id: 'notification.error', defaultMessage: 'An error occured' },
      });
    },
  });

  const isLoading = status !== 'success' && status !== 'error';

  useEffect(() => {
    trackUsage('didGoToMarketplace');
  }, [trackUsage]);

  if (isLoading) {
    return (
      <Layout>
        <Main aria-busy>
          <LoadingIndicatorPage />
        </Main>
      </Layout>
    );
  }

  return (
    <CheckPagePermissions permissions={adminPermissions.marketplace.main}>
      <Layout>
        <Main>
          <Helmet
            title={formatMessage({
              id: 'admin.pages.MarketPlacePage.helmet',
              defaultMessage: 'Marketplace - Plugins',
            })}
          />
          <HeaderLayout
            title={formatMessage({
              id: 'admin.pages.MarketPlacePage.title',
              defaultMessage: 'Marketplace',
            })}
            subtitle={formatMessage({
              id: 'admin.pages.MarketPlacePage.subtitle',
              defaultMessage: 'Get more out of Strapi',
            })}
          />
          <ContentLayout>
            <StackCentered
              size={0}
              hasRadius
              background="neutral0"
              shadow="tableShadow"
              paddingTop={10}
              paddingBottom={10}
            >
              <Box paddingBottom={7}>
                <Img
                  alt={formatMessage({
                    id: 'admin.pages.MarketPlacePage.illustration',
                    defaultMessage: 'marketplace illustration',
                  })}
                  src={MarketplacePicture}
                />
              </Box>
              <Typography variant="alpha">
                {formatMessage({
                  id: 'admin.pages.MarketPlacePage.coming-soon.1',
                  defaultMessage: 'A new way to make Strapi awesome.',
                })}
              </Typography>
              <Typography variant="alpha" textColor="primary700">
                {formatMessage({
                  id: 'admin.pages.MarketPlacePage.coming-soon.2',
                  defaultMessage: 'A new way to make Strapi awesome.',
                })}
              </Typography>
              <Flex maxWidth={pxToRem(580)} paddingTop={3}>
                <CenterTypography variant="epsilon" textColor="neutral600">
                  {formatMessage({
                    id: 'admin.pages.MarketPlacePage.content.subtitle',
                    defaultMessage:
                      'The new marketplace will help you get more out of Strapi. We are working hard to offer the best experience to discover and install plugins.',
                  })}
                </CenterTypography>
              </Flex>
              <Stack paddingTop={6} horizontal size={2}>
                {/* Temporarily hidden until we have the right URL for the link */}
                {/* <LinkButton href="https://strapi.io/" size="L" variant="secondary">
                  {formatMessage({
                    id: 'admin.pages.MarketPlacePage.submit.plugin.link',
                    defaultMessage: 'Submit your plugin',
                  })}
                </LinkButton> */}
                <LinkButton href="https://strapi.io/blog/strapi-market-is-coming-soon" size="L">
                  {formatMessage({
                    id: 'admin.pages.MarketPlacePage.blog.link',
                    defaultMessage: 'Read our blog post',
                  })}
                </LinkButton>
              </Stack>
            </StackCentered>
          </ContentLayout>
        </Main>
      </Layout>
    </CheckPagePermissions>
  );
};

export default MarketPlacePage;
<|endoftext|>


<commit_before>import React, { useState, useRef } from 'react';
import { Header } from '@buffetjs/custom';
import { Padded } from '@buffetjs/core';
import moment from 'moment';
import { Formik } from 'formik';
import { get, isEmpty } from 'lodash';
import { useIntl } from 'react-intl';
import { HeaderLayout, Button } from '@strapi/parts';
import { AddIcon, EditIcon } from '@strapi/icons';
import {
  BaselineAlignment,
  CheckPagePermissions,
  request,
  useTracking,
  useNotification,
  useOverlayBlocker,
} from '@strapi/helper-plugin';
import { useHistory, useRouteMatch } from 'react-router-dom';
import adminPermissions from '../../../../../admin/src/permissions';
import { useFetchPermissionsLayout, useFetchRole } from '../../../../../admin/src/hooks';
import PageTitle from '../../../../../admin/src/components/SettingsPageTitle';
import FormCard from '../../../../../admin/src/components/FormBloc';
import { ButtonWithNumber } from '../../../../../admin/src/components/Roles';
import SizedInput from '../../../../../admin/src/components/SizedInput';
import Permissions from '../../../../../admin/src/components/Roles/Permissions';

import schema from './utils/schema';

const CreatePage = () => {
  const toggleNotification = useNotification();
  const { lockApp, unlockApp } = useOverlayBlocker();
  const { formatMessage } = useIntl();
  const [isSubmiting, setIsSubmiting] = useState(false);
  const { replace } = useHistory();
  const permissionsRef = useRef();
  const { trackUsage } = useTracking();
  const params = useRouteMatch('/settings/roles/duplicate/:id');
  const id = get(params, 'params.id', null);
  const { isLoading: isLayoutLoading, data: permissionsLayout } = useFetchPermissionsLayout();
  const { permissions: rolePermissions, isLoading: isRoleLoading } = useFetchRole(id);

  const headerActions = (handleSubmit, handleReset) => [
    {
      label: formatMessage({
        id: 'app.components.Button.reset',
        defaultMessage: 'Reset',
      }),
      onClick: () => {
        handleReset();
        permissionsRef.current.resetForm();
      },
      color: 'cancel',
      type: 'button',
    },
    {
      label: formatMessage({
        id: 'app.components.Button.save',
        defaultMessage: 'Save',
      }),
      onClick: handleSubmit,
      color: 'success',
      type: 'submit',
      isLoading: isSubmiting,
    },
  ];

  const handleCreateRoleSubmit = data => {
    lockApp();
    setIsSubmiting(true);

    if (id) {
      trackUsage('willDuplicateRole');
    } else {
      trackUsage('willCreateNewRole');
    }

    Promise.resolve(
      request('/admin/roles', {
        method: 'POST',
        body: data,
      })
    )
      .then(async res => {
        const { permissionsToSend } = permissionsRef.current.getPermissions();

        if (id) {
          trackUsage('didDuplicateRole');
        } else {
          trackUsage('didCreateNewRole');
        }

        if (res.data.id && !isEmpty(permissionsToSend)) {
          await request(`/admin/roles/${res.data.id}/permissions`, {
            method: 'PUT',
            body: { permissions: permissionsToSend },
          });
        }

        return res;
      })
      .then(res => {
        setIsSubmiting(false);
        toggleNotification({
          type: 'success',
          message: { id: 'Settings.roles.created' },
        });
        replace(`/settings/roles/${res.data.id}`);
      })
      .catch(err => {
        console.error(err);
        setIsSubmiting(false);
        toggleNotification({
          type: 'warning',
          message: { id: 'notification.error' },
        });
      })
      .finally(() => {
        unlockApp();
      });
  };

  const actions = [
    <ButtonWithNumber number={0} onClick={() => console.log('Open user modal')} key="user-button">
      {formatMessage({
        id: 'Settings.roles.form.button.users-with-role',
        defaultMessage: 'Users with this role',
      })}
    </ButtonWithNumber>,
  ];

  const defaultDescription = `${formatMessage({
    id: 'Settings.roles.form.created',
  })} ${moment().format('LL')}`;

  return (
    <>
      <PageTitle name="Roles" />
      <Formik
        initialValues={{ name: '', description: defaultDescription }}
        onSubmit={handleCreateRoleSubmit}
        validationSchema={schema}
        validateOnChange={false}
      >
        {({ handleSubmit, values, errors, handleReset, handleChange, handleBlur }) => (
          <form onSubmit={handleSubmit}>
            <>
              <HeaderLayout
                primaryAction={<Button startIcon={<AddIcon />}>Add an entry</Button>}
                secondaryAction={(
                  <Button variant="tertiary" startIcon={<EditIcon />}>
                    Edit
                  </Button>
                )}
                title="Other CT"
                subtitle="36 entries found"
                as="h2"
              />
              <Header
                title={{
                  label: formatMessage({
                    id: 'Settings.roles.create.title',
                    defaultMessage: 'Create a role',
                  }),
                }}
                content={formatMessage({
                  id: 'Settings.roles.create.description',
                  defaultMessage: 'Define the rights given to the role',
                })}
                actions={headerActions(handleSubmit, handleReset)}
                isLoading={isLayoutLoading}
              />
              <BaselineAlignment top size="3px" />
              <FormCard
                actions={actions}
                title={formatMessage({
                  id: 'Settings.roles.form.title',
                  defaultMessage: 'Details',
                })}
                subtitle={formatMessage({
                  id: 'Settings.roles.form.description',
                  defaultMessage: 'Name and description of the role',
                })}
              >
                <SizedInput
                  label="Settings.roles.form.input.name"
                  defaultMessage="Name"
                  name="name"
                  type="text"
                  error={errors.name ? { id: errors.name } : null}
                  onBlur={handleBlur}
                  value={values.name}
                  onChange={handleChange}
                />

                <SizedInput
                  label="Settings.roles.form.input.description"
                  defaultMessage="Description"
                  name="description"
                  type="textarea"
                  onBlur={handleBlur}
                  value={values.description}
                  onChange={handleChange}
                  // Override the default height of the textarea
                  style={{ height: 115 }}
                />
              </FormCard>
              {!isLayoutLoading && !isRoleLoading && (
                <Padded top bottom size="md">
                  <Permissions
                    isFormDisabled={false}
                    ref={permissionsRef}
                    permissions={rolePermissions}
                    layout={permissionsLayout}
                  />
                </Padded>
              )}
            </>
          </form>
        )}
      </Formik>
    </>
  );
};

export default () => (
  <CheckPagePermissions permissions={adminPermissions.settings.roles.create}>
    <CreatePage />
  </CheckPagePermissions>
);

export { CreatePage };
<commit_msg>Update packages/core/admin/ee/admin/pages/Roles/CreatePage/index.js<commit_after>import React, { useState, useRef } from 'react';
import { Header } from '@buffetjs/custom';
import { Padded } from '@buffetjs/core';
import moment from 'moment';
import { Formik } from 'formik';
import { get, isEmpty } from 'lodash';
import { useIntl } from 'react-intl';
import { HeaderLayout, Button } from '@strapi/parts';
import { AddIcon, EditIcon } from '@strapi/icons';
import {
  BaselineAlignment,
  CheckPagePermissions,
  request,
  useTracking,
  useNotification,
  useOverlayBlocker,
} from '@strapi/helper-plugin';
import { useHistory, useRouteMatch } from 'react-router-dom';
import adminPermissions from '../../../../../admin/src/permissions';
import { useFetchPermissionsLayout, useFetchRole } from '../../../../../admin/src/hooks';
import PageTitle from '../../../../../admin/src/components/SettingsPageTitle';
import FormCard from '../../../../../admin/src/components/FormBloc';
import { ButtonWithNumber } from '../../../../../admin/src/components/Roles';
import SizedInput from '../../../../../admin/src/components/SizedInput';
import Permissions from '../../../../../admin/src/components/Roles/Permissions';

import schema from './utils/schema';

const CreatePage = () => {
  const toggleNotification = useNotification();
  const { lockApp, unlockApp } = useOverlayBlocker();
  const { formatMessage } = useIntl();
  const [isSubmiting, setIsSubmiting] = useState(false);
  const { replace } = useHistory();
  const permissionsRef = useRef();
  const { trackUsage } = useTracking();
  const params = useRouteMatch('/settings/roles/duplicate/:id');
  const id = get(params, 'params.id', null);
  const { isLoading: isLayoutLoading, data: permissionsLayout } = useFetchPermissionsLayout();
  const { permissions: rolePermissions, isLoading: isRoleLoading } = useFetchRole(id);

  const headerActions = (handleSubmit, handleReset) => [
    {
      label: formatMessage({
        id: 'app.components.Button.reset',
        defaultMessage: 'Reset',
      }),
      onClick: () => {
        handleReset();
        permissionsRef.current.resetForm();
      },
      color: 'cancel',
      type: 'button',
    },
    {
      label: formatMessage({
        id: 'app.components.Button.save',
        defaultMessage: 'Save',
      }),
      onClick: handleSubmit,
      color: 'success',
      type: 'submit',
      isLoading: isSubmiting,
    },
  ];

  const handleCreateRoleSubmit = data => {
    lockApp();
    setIsSubmiting(true);

    if (id) {
      trackUsage('willDuplicateRole');
    } else {
      trackUsage('willCreateNewRole');
    }

    Promise.resolve(
      request('/admin/roles', {
        method: 'POST',
        body: data,
      })
    )
      .then(async res => {
        const { permissionsToSend } = permissionsRef.current.getPermissions();

        if (id) {
          trackUsage('didDuplicateRole');
        } else {
          trackUsage('didCreateNewRole');
        }

        if (res.data.id && !isEmpty(permissionsToSend)) {
          await request(`/admin/roles/${res.data.id}/permissions`, {
            method: 'PUT',
            body: { permissions: permissionsToSend },
          });
        }

        return res;
      })
      .then(res => {
        setIsSubmiting(false);
        toggleNotification({
          type: 'success',
          message: { id: 'Settings.roles.created' },
        });
        replace(`/settings/roles/${res.data.id}`);
      })
      .catch(err => {
        console.error(err);
        setIsSubmiting(false);
        toggleNotification({
          type: 'warning',
          message: { id: 'notification.error' },
        });
      })
      .finally(() => {
        unlockApp();
      });
  };

  const actions = [
    <ButtonWithNumber number={0} onClick={() => console.log('Open user modal')} key="user-button">
      {formatMessage({
        id: 'Settings.roles.form.button.users-with-role',
        defaultMessage: 'Users with this role',
      })}
    </ButtonWithNumber>,
  ];

  const defaultDescription = `${formatMessage({
    id: 'Settings.roles.form.created',
  })} ${moment().format('LL')}`;

  return (
    <>
      <PageTitle name="Roles" />
      <Formik
        initialValues={{ name: '', description: defaultDescription }}
        onSubmit={handleCreateRoleSubmit}
        validationSchema={schema}
        validateOnChange={false}
      >
        {({ handleSubmit, values, errors, handleReset, handleChange, handleBlur }) => (
          <form onSubmit={handleSubmit}>
            <>
              <HeaderLayout
                primaryAction={<Button startIcon={<AddIcon />}>Add an entry</Button>}
                secondaryAction={(
                  <Button variant="tertiary" startIcon={<EditIcon />}>
                    Edit
                  </Button>
                )}
                title="Other CT"
                subtitle="36 entries found"
                as="h1"
              />
              <Header
                title={{
                  label: formatMessage({
                    id: 'Settings.roles.create.title',
                    defaultMessage: 'Create a role',
                  }),
                }}
                content={formatMessage({
                  id: 'Settings.roles.create.description',
                  defaultMessage: 'Define the rights given to the role',
                })}
                actions={headerActions(handleSubmit, handleReset)}
                isLoading={isLayoutLoading}
              />
              <BaselineAlignment top size="3px" />
              <FormCard
                actions={actions}
                title={formatMessage({
                  id: 'Settings.roles.form.title',
                  defaultMessage: 'Details',
                })}
                subtitle={formatMessage({
                  id: 'Settings.roles.form.description',
                  defaultMessage: 'Name and description of the role',
                })}
              >
                <SizedInput
                  label="Settings.roles.form.input.name"
                  defaultMessage="Name"
                  name="name"
                  type="text"
                  error={errors.name ? { id: errors.name } : null}
                  onBlur={handleBlur}
                  value={values.name}
                  onChange={handleChange}
                />

                <SizedInput
                  label="Settings.roles.form.input.description"
                  defaultMessage="Description"
                  name="description"
                  type="textarea"
                  onBlur={handleBlur}
                  value={values.description}
                  onChange={handleChange}
                  // Override the default height of the textarea
                  style={{ height: 115 }}
                />
              </FormCard>
              {!isLayoutLoading && !isRoleLoading && (
                <Padded top bottom size="md">
                  <Permissions
                    isFormDisabled={false}
                    ref={permissionsRef}
                    permissions={rolePermissions}
                    layout={permissionsLayout}
                  />
                </Padded>
              )}
            </>
          </form>
        )}
      </Formik>
    </>
  );
};

export default () => (
  <CheckPagePermissions permissions={adminPermissions.settings.roles.create}>
    <CreatePage />
  </CheckPagePermissions>
);

export { CreatePage };
<|endoftext|>