@slicemachine/init 1.1.9 → 1.1.10-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.js +410 -12
- package/build/index.js.map +1 -1
- package/jest.config.js +1 -0
- package/package.json +13 -3
- package/src/index.ts +14 -4
- package/src/steps/configure-project.ts +14 -3
- package/src/steps/display-final-message.ts +2 -1
- package/src/steps/index.ts +1 -0
- package/src/steps/install-required-dependencies.ts +29 -10
- package/src/steps/sendStarterData.ts +43 -0
- package/src/steps/starters/communication.ts +171 -0
- package/src/steps/starters/custom-types.ts +82 -0
- package/src/steps/starters/documents.ts +114 -0
- package/src/steps/starters/endpoints.ts +20 -0
- package/src/steps/starters/prompts.ts +29 -0
- package/src/steps/starters/s3.ts +201 -0
- package/src/steps/starters/slices.ts +62 -0
- package/src/utils/index.ts +5 -0
- package/.caches/eslint +0 -1
package/build/index.js
CHANGED
|
@@ -23,6 +23,16 @@ const tmp = require('tmp');
|
|
|
23
23
|
const AdmZip = require('adm-zip');
|
|
24
24
|
const fsExtra = require('fs-extra');
|
|
25
25
|
const fs = require('fs');
|
|
26
|
+
const cookie = require('@slicemachine/core/build/utils/cookie');
|
|
27
|
+
const Libraries = require('@slicemachine/core/build/libraries');
|
|
28
|
+
const models = require('@slicemachine/core/build/models');
|
|
29
|
+
const mime = require('mime');
|
|
30
|
+
const snakeCase = require('lodash.snakecase');
|
|
31
|
+
const FormData = require('form-data');
|
|
32
|
+
const uniqid = require('uniqid');
|
|
33
|
+
const customtypes = require('@prismicio/types-internal/lib/customtypes');
|
|
34
|
+
const Either$1 = require('fp-ts/lib/Either');
|
|
35
|
+
const t = require('io-ts');
|
|
26
36
|
|
|
27
37
|
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
28
38
|
|
|
@@ -55,12 +65,19 @@ const hapi__namespace = /*#__PURE__*/_interopNamespace(hapi);
|
|
|
55
65
|
const open__default = /*#__PURE__*/_interopDefaultLegacy(open);
|
|
56
66
|
const NodeUtils__namespace = /*#__PURE__*/_interopNamespace(NodeUtils);
|
|
57
67
|
const inquirer__namespace = /*#__PURE__*/_interopNamespace(inquirer);
|
|
68
|
+
const inquirer__default = /*#__PURE__*/_interopDefaultLegacy(inquirer);
|
|
58
69
|
const Separator__default = /*#__PURE__*/_interopDefaultLegacy(Separator);
|
|
59
70
|
const axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
|
|
60
71
|
const tmp__default = /*#__PURE__*/_interopDefaultLegacy(tmp);
|
|
61
72
|
const AdmZip__default = /*#__PURE__*/_interopDefaultLegacy(AdmZip);
|
|
62
73
|
const fsExtra__default = /*#__PURE__*/_interopDefaultLegacy(fsExtra);
|
|
63
74
|
const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
|
|
75
|
+
const Libraries__namespace = /*#__PURE__*/_interopNamespace(Libraries);
|
|
76
|
+
const mime__default = /*#__PURE__*/_interopDefaultLegacy(mime);
|
|
77
|
+
const snakeCase__default = /*#__PURE__*/_interopDefaultLegacy(snakeCase);
|
|
78
|
+
const FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData);
|
|
79
|
+
const uniqid__default = /*#__PURE__*/_interopDefaultLegacy(uniqid);
|
|
80
|
+
const t__namespace = /*#__PURE__*/_interopNamespace(t);
|
|
64
81
|
|
|
65
82
|
var __accessCheck = (obj, member, msg) => {
|
|
66
83
|
if (!member.has(obj))
|
|
@@ -374,6 +391,10 @@ function findArgument(args, name) {
|
|
|
374
391
|
return;
|
|
375
392
|
return flagValue;
|
|
376
393
|
}
|
|
394
|
+
function findFlag(args, name) {
|
|
395
|
+
const toFind = `--${name}`;
|
|
396
|
+
return args.includes(toFind);
|
|
397
|
+
}
|
|
377
398
|
const execCommand = util__default["default"].promisify(child_process.exec);
|
|
378
399
|
|
|
379
400
|
const {
|
|
@@ -403,16 +424,25 @@ function depsForFramework(framework) {
|
|
|
403
424
|
return "";
|
|
404
425
|
}
|
|
405
426
|
}
|
|
406
|
-
async function
|
|
407
|
-
const
|
|
408
|
-
const
|
|
409
|
-
const installDependencyCommand = yarnLock ? "yarn add" : "npm install --save";
|
|
410
|
-
const spinner = spinner$1("Downloading Slice Machine");
|
|
411
|
-
spinner.start();
|
|
427
|
+
async function addAndInstallDeps(framework, useYarn = false) {
|
|
428
|
+
const installDevDependencyCommand = useYarn ? "yarn add -D" : "npm install --save-dev";
|
|
429
|
+
const installDependencyCommand = useYarn ? "yarn add" : "npm install --save";
|
|
412
430
|
const { stderr } = await execCommand(`${installDevDependencyCommand} ${SM_PACKAGE_NAME}`);
|
|
413
431
|
const deps = depsForFramework(framework);
|
|
414
432
|
if (deps)
|
|
415
433
|
await execCommand(`${installDependencyCommand} ${deps}`);
|
|
434
|
+
return stderr;
|
|
435
|
+
}
|
|
436
|
+
async function installDeps(useYarn = false) {
|
|
437
|
+
const installCommand = useYarn ? "yarn" : "npm install";
|
|
438
|
+
const { stderr } = await execCommand(installCommand);
|
|
439
|
+
return stderr;
|
|
440
|
+
}
|
|
441
|
+
async function installRequiredDependencies(cwd, framework, skipDependencies) {
|
|
442
|
+
const yarnLock = NodeUtils__namespace.Files.exists(NodeUtils__namespace.YarnLockPath(cwd));
|
|
443
|
+
const spinner = spinner$1("Installing Slice Machine");
|
|
444
|
+
spinner.start();
|
|
445
|
+
const stderr = await (skipDependencies ? installDeps(yarnLock) : addAndInstallDeps(framework, yarnLock));
|
|
416
446
|
const pathToPkg = path__default["default"].join(NodeUtils__namespace.PackagePaths(cwd).value(), SM_PACKAGE_NAME);
|
|
417
447
|
const isPackageInstalled = NodeUtils__namespace.Files.exists(pathToPkg);
|
|
418
448
|
if (isPackageInstalled || !stderr.length) {
|
|
@@ -672,17 +702,19 @@ async function loginOrBypass(base) {
|
|
|
672
702
|
|
|
673
703
|
const defaultSliceMachineVersion = "0.0.41";
|
|
674
704
|
async function configureProject(cwd, base, repositoryDomainName, framework, sliceLibPath = [], tracking = true) {
|
|
675
|
-
const
|
|
705
|
+
const frameworkName = NodeUtils__namespace.Framework.fancyName(framework.value);
|
|
706
|
+
const spinner = spinner$1(`Configuring your ${frameworkName} and Prismic project...`);
|
|
676
707
|
spinner.start();
|
|
677
708
|
try {
|
|
678
709
|
const manifest = NodeUtils__namespace.retrieveManifest(cwd);
|
|
679
710
|
const packageJson = NodeUtils__namespace.retrieveJsonPackage(cwd);
|
|
680
711
|
const sliceMachineVersionInstalled = getTheSliceMachineVersionInstalled(packageJson);
|
|
681
712
|
const manifestAlreadyExistWithContent = manifest.exists && manifest.content;
|
|
713
|
+
const libs = manifest.content && manifest.content.libraries && manifest.content.libraries.length > 0 ? manifest.content.libraries : ["@/slices"];
|
|
682
714
|
const manifestUpdated = {
|
|
683
715
|
...manifestAlreadyExistWithContent ? manifest.content : { _latest: sliceMachineVersionInstalled },
|
|
684
716
|
apiEndpoint: Prismic__namespace.Endpoints.buildRepositoryEndpoint(base, repositoryDomainName),
|
|
685
|
-
libraries: [
|
|
717
|
+
libraries: [...libs, ...sliceLibPath],
|
|
686
718
|
...framework.manuallyAdded ? { framework: framework.value } : {},
|
|
687
719
|
...!tracking ? { tracking } : {}
|
|
688
720
|
};
|
|
@@ -691,7 +723,7 @@ async function configureProject(cwd, base, repositoryDomainName, framework, slic
|
|
|
691
723
|
else
|
|
692
724
|
NodeUtils__namespace.patchManifest(cwd, manifestUpdated);
|
|
693
725
|
const pathToSlicesFolder = NodeUtils__namespace.CustomPaths(cwd).library("slices").value();
|
|
694
|
-
if (!NodeUtils__namespace.Files.exists(pathToSlicesFolder)) {
|
|
726
|
+
if (!NodeUtils__namespace.Files.exists(pathToSlicesFolder) && libs.includes("@/slices")) {
|
|
695
727
|
NodeUtils__namespace.Files.mkdir(pathToSlicesFolder, { recursive: true });
|
|
696
728
|
}
|
|
697
729
|
NodeUtils__namespace.addJsonPackageSmScript(cwd);
|
|
@@ -729,7 +761,8 @@ const extractVersionNumberFromSemver = (semver) => {
|
|
|
729
761
|
function displayFinalMessage(cwd) {
|
|
730
762
|
const yarnLock = NodeUtils__namespace.Files.exists(NodeUtils__namespace.YarnLockPath(cwd));
|
|
731
763
|
const command = `${yarnLock ? "yarn" : "npm"} run ${core.CONSTS.SCRIPT_NAME}`;
|
|
732
|
-
console.log(
|
|
764
|
+
console.log();
|
|
765
|
+
console.log(`${white("\u25A0")} Run ${purple(command)} to start Slice Machine`);
|
|
733
766
|
}
|
|
734
767
|
|
|
735
768
|
const Dependencies = {
|
|
@@ -837,6 +870,369 @@ async function installLib(cwd, libGithubPath, branch = "HEAD") {
|
|
|
837
870
|
}
|
|
838
871
|
}
|
|
839
872
|
|
|
873
|
+
function handleErrors(prefix, err) {
|
|
874
|
+
if (axios__default["default"].isAxiosError(err) && err.response) {
|
|
875
|
+
writeError$1(`${prefix} | [${err.response.status}]: ${err.response.statusText}`);
|
|
876
|
+
} else if (err instanceof Error) {
|
|
877
|
+
writeError$1(`${prefix} ${err.message}`);
|
|
878
|
+
} else {
|
|
879
|
+
writeError$1(`${prefix} ${String(err)}`);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
async function getRemoteSliceIds(customTypeApiEndpoint, repository, authorization) {
|
|
883
|
+
const addr = `${stripLastSlash(customTypeApiEndpoint)}/slices`;
|
|
884
|
+
return axios__default["default"].get(addr, {
|
|
885
|
+
headers: {
|
|
886
|
+
Authorization: `Bearer ${authorization}`,
|
|
887
|
+
repository
|
|
888
|
+
}
|
|
889
|
+
}).then((res) => {
|
|
890
|
+
return Array.isArray(res.data) ? res.data.map((model) => model.id) : [];
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
async function sendModelToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, model) {
|
|
894
|
+
const data = models.Slices.fromSM(model);
|
|
895
|
+
const updateOrInsertUrl = `${customTypesApiEndpoint}slices/${remoteSliceIds.includes(model.id) ? "update" : "insert"}`;
|
|
896
|
+
return axios__default["default"].post(updateOrInsertUrl, data, {
|
|
897
|
+
headers: {
|
|
898
|
+
Authorization: `Bearer ${authorization}`,
|
|
899
|
+
repository
|
|
900
|
+
}
|
|
901
|
+
}).then(() => {
|
|
902
|
+
return;
|
|
903
|
+
}).catch((err) => {
|
|
904
|
+
handleErrors(`sending slice ${model.id}, please try again. If the problem persists, contact us.`, err);
|
|
905
|
+
throw err;
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
async function sendManyModelsToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, models) {
|
|
909
|
+
return Promise.all(models.map((model) => sendModelToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, model))).then(() => {
|
|
910
|
+
return;
|
|
911
|
+
}).catch(() => {
|
|
912
|
+
process.exit(1);
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
function stripLastSlash(str) {
|
|
916
|
+
return str.replace(/\/*$/g, "");
|
|
917
|
+
}
|
|
918
|
+
function getRemoteCustomTypeIds(customTypeApiEndpoint, repository, authorization) {
|
|
919
|
+
const addr = `${stripLastSlash(customTypeApiEndpoint)}/customtypes`;
|
|
920
|
+
return axios__default["default"].get(addr, {
|
|
921
|
+
headers: {
|
|
922
|
+
Authorization: `Bearer ${authorization}`,
|
|
923
|
+
repository
|
|
924
|
+
}
|
|
925
|
+
}).then((res) => {
|
|
926
|
+
return Array.isArray(res.data) ? res.data.map((ct) => ct.id) : [];
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
async function sendCustomTypeToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customType) {
|
|
930
|
+
const shouldUpdate = remoteCustomTypeIds.includes(customType.id);
|
|
931
|
+
const addr = `${stripLastSlash(customTypeApiEndpoint)}/customtypes/${shouldUpdate ? "update" : "insert"}`;
|
|
932
|
+
return axios__default["default"].post(addr, customType, {
|
|
933
|
+
headers: {
|
|
934
|
+
repository,
|
|
935
|
+
Authorization: `Bearer ${authorization}`
|
|
936
|
+
}
|
|
937
|
+
}).then(() => {
|
|
938
|
+
return;
|
|
939
|
+
}).catch((err) => {
|
|
940
|
+
handleErrors(`sending custom type ${customType.id}, please try again. If the problem persists, contact us.`, err);
|
|
941
|
+
throw err;
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
async function sendManyCustomTypesToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customTypes) {
|
|
945
|
+
return Promise.all(customTypes.map((customType) => sendCustomTypeToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customType))).then(() => {
|
|
946
|
+
return;
|
|
947
|
+
}).catch(() => {
|
|
948
|
+
process.exit(1);
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
const ProductionApisEndpoints = {
|
|
953
|
+
Models: "https://customtypes.prismic.io/",
|
|
954
|
+
AclProvider: "https://0yyeb2g040.execute-api.us-east-1.amazonaws.com/prod/"
|
|
955
|
+
};
|
|
956
|
+
const StageApisEndpoints = {
|
|
957
|
+
Models: "https://customtypes.wroom.io/",
|
|
958
|
+
AclProvider: "https://2iamcvnxf4.execute-api.us-east-1.amazonaws.com/stage/"
|
|
959
|
+
};
|
|
960
|
+
const getEndpointsFromBase = (base) => {
|
|
961
|
+
const url = new URL(base);
|
|
962
|
+
if (url.hostname === "wroom.io")
|
|
963
|
+
return StageApisEndpoints;
|
|
964
|
+
return ProductionApisEndpoints;
|
|
965
|
+
};
|
|
966
|
+
|
|
967
|
+
async function promptToPushSlices() {
|
|
968
|
+
return inquirer__default["default"].prompt([
|
|
969
|
+
{
|
|
970
|
+
type: "confirm",
|
|
971
|
+
name: "pushSlices",
|
|
972
|
+
default: false,
|
|
973
|
+
message: "Your repository already contains Slices. Do you want to continue pushing your local Slices?"
|
|
974
|
+
}
|
|
975
|
+
]).then((res) => res.pushSlices);
|
|
976
|
+
}
|
|
977
|
+
async function promptToPushCustomTypes() {
|
|
978
|
+
return inquirer__default["default"].prompt([
|
|
979
|
+
{
|
|
980
|
+
type: "confirm",
|
|
981
|
+
name: "pushCustomTypes",
|
|
982
|
+
default: false,
|
|
983
|
+
message: "Your repository already contains Custom Types. Do you want to continue pushing your local Slices?"
|
|
984
|
+
}
|
|
985
|
+
]).then((res) => res.pushCustomTypes);
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
async function createAcl(address, repository, authorization) {
|
|
989
|
+
return axios__default["default"].get(address + "create", {
|
|
990
|
+
headers: {
|
|
991
|
+
repository,
|
|
992
|
+
Authorization: `Bearer ${authorization}`,
|
|
993
|
+
"User-Agent": "slice-machine"
|
|
994
|
+
}
|
|
995
|
+
}).then((res) => res.data);
|
|
996
|
+
}
|
|
997
|
+
async function createFormForS3(key, filename, filePath, acl) {
|
|
998
|
+
const form = new FormData__default["default"]();
|
|
999
|
+
Object.entries(acl.values.fields).forEach(([k, value]) => {
|
|
1000
|
+
form.append(k, value);
|
|
1001
|
+
});
|
|
1002
|
+
form.append("key", key);
|
|
1003
|
+
const contentType = mime__default["default"].getType(filePath);
|
|
1004
|
+
contentType && form.append("Content-Type", contentType);
|
|
1005
|
+
return fs__default["default"].promises.readFile(filePath).then((file) => {
|
|
1006
|
+
form.append("file", file, { filename });
|
|
1007
|
+
return form;
|
|
1008
|
+
}).catch(() => {
|
|
1009
|
+
writeError$1(`Error reading preview image: ${filename}`);
|
|
1010
|
+
return null;
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
function createS3Key(repository, sliceName, variationId, filename) {
|
|
1014
|
+
return `${repository}/shared-slices/${snakeCase__default["default"](sliceName)}/${snakeCase__default["default"](variationId)}-${uniqid__default["default"]()}/${filename}`;
|
|
1015
|
+
}
|
|
1016
|
+
async function sendVariationPreviewToS3(acl, repository, sliceName, variationId, filePath) {
|
|
1017
|
+
const filename = path__default["default"].basename(filePath);
|
|
1018
|
+
const key = createS3Key(repository, sliceName, variationId, filename);
|
|
1019
|
+
const form = await createFormForS3(key, filename, filePath, acl);
|
|
1020
|
+
if (form === null)
|
|
1021
|
+
return null;
|
|
1022
|
+
if (form.hasKnownLength() === false) {
|
|
1023
|
+
writeError$1(`[slice/push] An error occurred while uploading preview image ${filePath} as length in unknown`);
|
|
1024
|
+
}
|
|
1025
|
+
const errorMessage = `[slice/push] An error occurred while uploading preview images for ${sliceName}-${variationId} - please contact support`;
|
|
1026
|
+
return axios__default["default"].post(acl.values.url, form, {
|
|
1027
|
+
headers: {
|
|
1028
|
+
...form.getHeaders(),
|
|
1029
|
+
"Content-Length": String(form.getLengthSync())
|
|
1030
|
+
}
|
|
1031
|
+
}).then((res) => {
|
|
1032
|
+
if (res.status !== 204) {
|
|
1033
|
+
writeError$1(errorMessage);
|
|
1034
|
+
writeError$1(`${res.status}: ${res.statusText}`);
|
|
1035
|
+
return null;
|
|
1036
|
+
} else {
|
|
1037
|
+
return `${acl.imgixEndpoint}/${key}`;
|
|
1038
|
+
}
|
|
1039
|
+
}).catch((err) => {
|
|
1040
|
+
writeError$1(errorMessage);
|
|
1041
|
+
if (axios__default["default"].isAxiosError(err) && err.response) {
|
|
1042
|
+
writeError$1(`${err.response.status}: ${err.response.statusText}`);
|
|
1043
|
+
} else if (err instanceof Error) {
|
|
1044
|
+
writeError$1(err.message);
|
|
1045
|
+
} else {
|
|
1046
|
+
writeError$1(String(err));
|
|
1047
|
+
}
|
|
1048
|
+
return null;
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
async function maybeAddImageUrlToVariation(acl, repository, modelId, pathToScreenShot, variation) {
|
|
1052
|
+
const imageUrl = await sendVariationPreviewToS3(acl, repository, modelId, variation.id, pathToScreenShot);
|
|
1053
|
+
if (!imageUrl)
|
|
1054
|
+
return variation;
|
|
1055
|
+
return {
|
|
1056
|
+
...variation,
|
|
1057
|
+
imageUrl
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
async function addImageUrlsToVariations(acl, repository, modelId, screenshotPaths, variations) {
|
|
1061
|
+
return Promise.all(variations.map(async (variation) => {
|
|
1062
|
+
const screenshot = screenshotPaths[variation.id];
|
|
1063
|
+
if (!screenshot || !screenshot.path)
|
|
1064
|
+
return variation;
|
|
1065
|
+
return maybeAddImageUrlToVariation(acl, repository, modelId, screenshot.path, variation);
|
|
1066
|
+
}));
|
|
1067
|
+
}
|
|
1068
|
+
async function maybeUpdateModelVariationsWithImageUrl(acl, repository, component) {
|
|
1069
|
+
const { screenshotPaths, model } = component;
|
|
1070
|
+
const variations = await addImageUrlsToVariations(acl, repository, model.id, screenshotPaths, model.variations);
|
|
1071
|
+
return {
|
|
1072
|
+
...model,
|
|
1073
|
+
variations
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
async function addImageUrlsToModelVariations(acl, repository, components) {
|
|
1077
|
+
return Promise.all(components.map(async (component) => maybeUpdateModelVariationsWithImageUrl(acl, repository, component)));
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
async function sendSlicesFromStarter(base, repository, authorization, libraryPaths, cwd) {
|
|
1081
|
+
const endpoints = getEndpointsFromBase(base);
|
|
1082
|
+
const libraries = Libraries__namespace.libraries(cwd, libraryPaths);
|
|
1083
|
+
if (libraries.length === 0)
|
|
1084
|
+
return Promise.resolve(false);
|
|
1085
|
+
const remoteSlices = await getRemoteSliceIds(endpoints.Models, repository, authorization);
|
|
1086
|
+
if (remoteSlices.length) {
|
|
1087
|
+
const pushAnyway = await promptToPushSlices();
|
|
1088
|
+
if (pushAnyway === false)
|
|
1089
|
+
return Promise.resolve(true);
|
|
1090
|
+
}
|
|
1091
|
+
const spinner = spinner$1("Pushing existing Slice models to your repository");
|
|
1092
|
+
spinner.start();
|
|
1093
|
+
const acl = await createAcl(endpoints.AclProvider, repository, authorization);
|
|
1094
|
+
const components = libraries.reduce((acc, lib) => {
|
|
1095
|
+
return [...acc, ...lib.components];
|
|
1096
|
+
}, []);
|
|
1097
|
+
const models = await addImageUrlsToModelVariations(acl, repository, components);
|
|
1098
|
+
await sendManyModelsToPrismic(repository, authorization, endpoints.Models, remoteSlices, models);
|
|
1099
|
+
spinner.succeed();
|
|
1100
|
+
return Promise.resolve(true);
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
function readCustomTypes(cwd) {
|
|
1104
|
+
const customTypePaths = NodeUtils.CustomTypesPaths(cwd);
|
|
1105
|
+
const dir = customTypePaths.value();
|
|
1106
|
+
if (NodeUtils.Files.isDirectory(dir) === false)
|
|
1107
|
+
return [];
|
|
1108
|
+
const fileNames = NodeUtils.Files.readDirectory(dir);
|
|
1109
|
+
const files = fileNames.reduce((acc, fileName) => {
|
|
1110
|
+
const filePath = customTypePaths.customType(fileName).model();
|
|
1111
|
+
const json = NodeUtils.Files.safeReadJson(filePath);
|
|
1112
|
+
if (!json)
|
|
1113
|
+
return acc;
|
|
1114
|
+
const file = customtypes.CustomType.decode(json);
|
|
1115
|
+
if (file instanceof Error) {
|
|
1116
|
+
writeError$1(`reading ${filePath}: ${file.message}`);
|
|
1117
|
+
return acc;
|
|
1118
|
+
}
|
|
1119
|
+
if (Either$1.isLeft(file)) {
|
|
1120
|
+
writeError$1(`validating ${filePath}: ${JSON.stringify(file.left)}`);
|
|
1121
|
+
return acc;
|
|
1122
|
+
}
|
|
1123
|
+
return [...acc, file.right];
|
|
1124
|
+
}, []);
|
|
1125
|
+
return files;
|
|
1126
|
+
}
|
|
1127
|
+
async function sendCustomTypesFromStarter(repository, authorization, base, cwd) {
|
|
1128
|
+
const customTypeApiEndpoint = getEndpointsFromBase(base).Models;
|
|
1129
|
+
const customTypes = readCustomTypes(cwd);
|
|
1130
|
+
if (customTypes.length === 0)
|
|
1131
|
+
return Promise.resolve(false);
|
|
1132
|
+
const remoteCustomTypeIds = await getRemoteCustomTypeIds(customTypeApiEndpoint, repository, authorization);
|
|
1133
|
+
if (remoteCustomTypeIds.length) {
|
|
1134
|
+
const shouldPush = await promptToPushCustomTypes();
|
|
1135
|
+
if (shouldPush === false)
|
|
1136
|
+
return Promise.resolve(false);
|
|
1137
|
+
}
|
|
1138
|
+
const spinner = spinner$1("Pushing existing custom types to your repository");
|
|
1139
|
+
spinner.start();
|
|
1140
|
+
await sendManyCustomTypesToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customTypes);
|
|
1141
|
+
spinner.succeed();
|
|
1142
|
+
return Promise.resolve(true);
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
const SignatureFileReader = t__namespace.type({
|
|
1146
|
+
signature: t__namespace.string
|
|
1147
|
+
});
|
|
1148
|
+
async function readSignatureFile(cwd) {
|
|
1149
|
+
const pathToFile = path__default["default"].join(cwd, "documents", "index.json");
|
|
1150
|
+
return fs__default["default"].promises.readFile(pathToFile, "utf-8").then((res) => {
|
|
1151
|
+
const data = JSON.parse(res);
|
|
1152
|
+
return Either.getOrElseW(() => {
|
|
1153
|
+
throw new Error("Unable to read document signature file");
|
|
1154
|
+
})(SignatureFileReader.decode(data));
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
async function lsdir(dir) {
|
|
1158
|
+
return fs__default["default"].promises.readdir(dir).then((dirs) => {
|
|
1159
|
+
return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isDirectory()).map((subdirectory) => path__default["default"].join(dir, subdirectory));
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
async function lsfiles(dir) {
|
|
1163
|
+
return fs__default["default"].promises.readdir(dir).then((dirs) => {
|
|
1164
|
+
return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isFile()).map((file) => path__default["default"].join(dir, file));
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
async function readDocuments(cwd) {
|
|
1168
|
+
const documentDir = path__default["default"].join(cwd, "documents");
|
|
1169
|
+
const dirs = await lsdir(documentDir);
|
|
1170
|
+
const files = (await Promise.all(dirs.map((dir) => lsfiles(dir)))).flat();
|
|
1171
|
+
const documentObj = files.reduce((acc, file) => {
|
|
1172
|
+
const fileContent = fs__default["default"].readFileSync(file, "utf-8");
|
|
1173
|
+
const filename = path__default["default"].parse(file).name;
|
|
1174
|
+
acc[filename] = JSON.parse(fileContent);
|
|
1175
|
+
return acc;
|
|
1176
|
+
}, {});
|
|
1177
|
+
return JSON.stringify(documentObj);
|
|
1178
|
+
}
|
|
1179
|
+
const sendDocumentsFromStarter = async (repository, cookies, base, cwd) => {
|
|
1180
|
+
const pathToDocuments = path__default["default"].join(cwd, "documents");
|
|
1181
|
+
const pathToSignatureFile = path__default["default"].join(pathToDocuments, "index.json");
|
|
1182
|
+
if (!fs__default["default"].existsSync(pathToSignatureFile)) {
|
|
1183
|
+
return Promise.resolve(false);
|
|
1184
|
+
}
|
|
1185
|
+
const signatureObj = await readSignatureFile(cwd);
|
|
1186
|
+
const documentsStr = await readDocuments(cwd);
|
|
1187
|
+
const payload = {
|
|
1188
|
+
signature: signatureObj.signature,
|
|
1189
|
+
documents: documentsStr
|
|
1190
|
+
};
|
|
1191
|
+
const prismicUrl = new URL(base);
|
|
1192
|
+
prismicUrl.hostname = `${repository}.${prismicUrl.hostname}`;
|
|
1193
|
+
prismicUrl.pathname = "starter/documents";
|
|
1194
|
+
const endpointURL = prismicUrl.toString();
|
|
1195
|
+
const spinner = spinner$1("Pushing existing documents to your repository");
|
|
1196
|
+
spinner.start();
|
|
1197
|
+
return axios__default["default"].post(endpointURL, payload, {
|
|
1198
|
+
headers: {
|
|
1199
|
+
"User-Agent": "prismic-cli/0",
|
|
1200
|
+
Cookie: cookies
|
|
1201
|
+
}
|
|
1202
|
+
}).then(() => {
|
|
1203
|
+
spinner.succeed();
|
|
1204
|
+
fs__default["default"].rmSync(pathToDocuments, { recursive: true, force: true });
|
|
1205
|
+
return true;
|
|
1206
|
+
}).catch((e) => {
|
|
1207
|
+
var _a;
|
|
1208
|
+
spinner.fail();
|
|
1209
|
+
if (((_a = e.response) == null ? void 0 : _a.data) === "Repository should not contain documents") {
|
|
1210
|
+
writeError$1("The selected repository is not empty, documents cannot be uploaded. Please choose an empty repository or delete the documents contained in your repository.");
|
|
1211
|
+
} else {
|
|
1212
|
+
handleErrors("sending documents, please try again. If the problem persists, contact us.", e);
|
|
1213
|
+
}
|
|
1214
|
+
process.exit(1);
|
|
1215
|
+
});
|
|
1216
|
+
};
|
|
1217
|
+
|
|
1218
|
+
async function sendStarterData(repository, base, cookies, sendDocs = true, cwd) {
|
|
1219
|
+
const smJson = NodeUtils.retrieveManifest(cwd);
|
|
1220
|
+
const pathToDocuments = path__default["default"].join(cwd, "documents");
|
|
1221
|
+
const hasDocuments = NodeUtils.Files.exists(pathToDocuments);
|
|
1222
|
+
if (smJson.exists === false || hasDocuments === false)
|
|
1223
|
+
return Promise.resolve(false);
|
|
1224
|
+
const authTokenFromCookie = cookie.parsePrismicAuthToken(cookies);
|
|
1225
|
+
if (smJson.content && smJson.content.libraries) {
|
|
1226
|
+
await sendSlicesFromStarter(base, repository, authTokenFromCookie, smJson.content.libraries, cwd);
|
|
1227
|
+
}
|
|
1228
|
+
await sendCustomTypesFromStarter(repository, authTokenFromCookie, base, cwd);
|
|
1229
|
+
if (sendDocs === false) {
|
|
1230
|
+
fs__default["default"].rmSync(pathToDocuments, { recursive: true, force: true });
|
|
1231
|
+
return Promise.resolve(true);
|
|
1232
|
+
}
|
|
1233
|
+
return sendDocumentsFromStarter(repository, cookies, base, cwd);
|
|
1234
|
+
}
|
|
1235
|
+
|
|
840
1236
|
async function init() {
|
|
841
1237
|
const cwd = findArgument(process.argv, "cwd") || process.cwd();
|
|
842
1238
|
const base = findArgument(process.argv, "base") || core.CONSTS.DEFAULT_BASE;
|
|
@@ -844,7 +1240,8 @@ async function init() {
|
|
|
844
1240
|
const branch = findArgument(process.argv, "branch");
|
|
845
1241
|
const isTrackingAvailable = findArgument(process.argv, "tracking") !== "false";
|
|
846
1242
|
const maybeRepositorySubdomain = findArgument(process.argv, "repository");
|
|
847
|
-
|
|
1243
|
+
const sendDocs = findFlag(process.argv, "no-docs");
|
|
1244
|
+
Tracker.get().initialize("JfTfmHaATChc4xueS7RcCBsixI71dJIJ" , isTrackingAvailable);
|
|
848
1245
|
void Tracker.get().trackInitStart(maybeRepositorySubdomain);
|
|
849
1246
|
console.log(purple("You're about to configure Slicemachine... Press ctrl + C to cancel"));
|
|
850
1247
|
validatePkg(cwd);
|
|
@@ -859,9 +1256,10 @@ async function init() {
|
|
|
859
1256
|
const frameworkResult = await detectFramework(cwd);
|
|
860
1257
|
const repositoryDomainName = await chooseOrCreateARepository(cwd, frameworkResult.value, config.cookies, config.base, maybeRepositorySubdomain);
|
|
861
1258
|
Tracker.get().setRepository(repositoryDomainName);
|
|
862
|
-
await installRequiredDependencies(cwd, frameworkResult.value);
|
|
863
1259
|
const sliceLibPath = lib ? await installLib(cwd, lib, branch) : void 0;
|
|
1260
|
+
const wasStarter = await sendStarterData(repositoryDomainName, config.base, config.cookies, sendDocs, cwd);
|
|
864
1261
|
await configureProject(cwd, base, repositoryDomainName, frameworkResult, sliceLibPath, isTrackingAvailable);
|
|
1262
|
+
await installRequiredDependencies(cwd, frameworkResult.value, wasStarter);
|
|
865
1263
|
displayFinalMessage(cwd);
|
|
866
1264
|
}
|
|
867
1265
|
init().then(() => {
|