@slicemachine/init 1.1.10-alpha.4 → 1.1.11-alpha.1
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 +273 -389
- package/build/index.js.map +1 -1
- package/package.json +4 -11
- package/src/index.ts +36 -32
- package/src/steps/choose-or-create-a-repository.ts +43 -42
- package/src/steps/configure-project.ts +3 -5
- package/src/steps/loginOrBypass.ts +18 -14
- package/src/steps/sendStarterData.ts +18 -30
- package/src/steps/starters/custom-types.ts +29 -30
- package/src/steps/starters/documents.ts +30 -55
- package/src/steps/starters/prompts.ts +1 -1
- package/src/steps/starters/s3.ts +51 -182
- package/src/steps/starters/slices.ts +55 -42
- package/src/utils/auth/helpers.ts +5 -1
- package/src/utils/auth/index.ts +30 -30
- package/src/utils/client.ts +67 -0
- package/src/utils/create-repo.ts +9 -15
- package/src/utils/fs.ts +18 -0
- package/src/utils/index.ts +16 -0
- package/src/utils/validateRepositoryName.ts +44 -0
- package/src/steps/starters/communication.ts +0 -171
- package/src/steps/starters/endpoints.ts +0 -20
- package/src/utils/communication.ts +0 -72
package/build/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
'use strict';
|
|
4
4
|
|
|
5
|
-
const
|
|
5
|
+
const client = require('@slicemachine/client');
|
|
6
6
|
const Prismic = require('@slicemachine/core/build/prismic');
|
|
7
7
|
const ServerAnalytics = require('analytics-node');
|
|
8
8
|
const uuid = require('uuid');
|
|
@@ -11,28 +11,24 @@ const util = require('util');
|
|
|
11
11
|
const child_process = require('child_process');
|
|
12
12
|
const chalk = require('chalk');
|
|
13
13
|
const ora = require('ora');
|
|
14
|
+
const core = require('@slicemachine/core');
|
|
14
15
|
const hapi = require('@hapi/hapi');
|
|
15
16
|
const open = require('open');
|
|
17
|
+
const t = require('io-ts');
|
|
18
|
+
const fs = require('fs');
|
|
16
19
|
const NodeUtils = require('@slicemachine/core/build/node-utils');
|
|
17
20
|
const inquirer = require('inquirer');
|
|
18
21
|
const Separator = require('inquirer/lib/objects/separator');
|
|
19
|
-
const axios = require('axios');
|
|
20
|
-
const _function = require('fp-ts/function');
|
|
21
|
-
const Either = require('fp-ts/Either');
|
|
22
22
|
const tmp = require('tmp');
|
|
23
23
|
const AdmZip = require('adm-zip');
|
|
24
24
|
const fsExtra = require('fs-extra');
|
|
25
|
-
const
|
|
26
|
-
const
|
|
27
|
-
const Libraries = require('@slicemachine/core/build/libraries');
|
|
25
|
+
const axios = require('axios');
|
|
26
|
+
const Either = require('fp-ts/Either');
|
|
28
27
|
const models = require('@slicemachine/core/build/models');
|
|
29
|
-
const
|
|
30
|
-
const snakeCase = require('lodash.snakecase');
|
|
31
|
-
const FormData = require('form-data');
|
|
32
|
-
const uniqid = require('uniqid');
|
|
28
|
+
const Libraries = require('@slicemachine/core/build/libraries');
|
|
33
29
|
const customtypes = require('@prismicio/types-internal/lib/customtypes');
|
|
34
30
|
const Either$1 = require('fp-ts/lib/Either');
|
|
35
|
-
const
|
|
31
|
+
const SharedConfig = require('@slicemachine/core/build/prismic/SharedConfig');
|
|
36
32
|
|
|
37
33
|
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
38
34
|
|
|
@@ -63,21 +59,17 @@ const chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
|
|
|
63
59
|
const ora__default = /*#__PURE__*/_interopDefaultLegacy(ora);
|
|
64
60
|
const hapi__namespace = /*#__PURE__*/_interopNamespace(hapi);
|
|
65
61
|
const open__default = /*#__PURE__*/_interopDefaultLegacy(open);
|
|
62
|
+
const t__namespace = /*#__PURE__*/_interopNamespace(t);
|
|
63
|
+
const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
|
|
66
64
|
const NodeUtils__namespace = /*#__PURE__*/_interopNamespace(NodeUtils);
|
|
67
65
|
const inquirer__namespace = /*#__PURE__*/_interopNamespace(inquirer);
|
|
68
66
|
const inquirer__default = /*#__PURE__*/_interopDefaultLegacy(inquirer);
|
|
69
67
|
const Separator__default = /*#__PURE__*/_interopDefaultLegacy(Separator);
|
|
70
|
-
const axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
|
|
71
68
|
const tmp__default = /*#__PURE__*/_interopDefaultLegacy(tmp);
|
|
72
69
|
const AdmZip__default = /*#__PURE__*/_interopDefaultLegacy(AdmZip);
|
|
73
70
|
const fsExtra__default = /*#__PURE__*/_interopDefaultLegacy(fsExtra);
|
|
74
|
-
const
|
|
71
|
+
const axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
|
|
75
72
|
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);
|
|
81
73
|
|
|
82
74
|
var __accessCheck = (obj, member, msg) => {
|
|
83
75
|
if (!member.has(obj))
|
|
@@ -98,6 +90,13 @@ var __privateSet = (obj, member, value, setter) => {
|
|
|
98
90
|
return value;
|
|
99
91
|
};
|
|
100
92
|
var _client, _isTrackingActive, _anonymousId, _userId, _repository;
|
|
93
|
+
var EventType;
|
|
94
|
+
(function(EventType2) {
|
|
95
|
+
EventType2["DownloadLibrary"] = "SliceMachine Download Library";
|
|
96
|
+
EventType2["InitStart"] = "SliceMachine Init Start";
|
|
97
|
+
EventType2["InitIdentify"] = "SliceMachine Init Identify";
|
|
98
|
+
EventType2["InitDone"] = "SliceMachine Init Done";
|
|
99
|
+
})(EventType || (EventType = {}));
|
|
101
100
|
class InitTracker {
|
|
102
101
|
constructor() {
|
|
103
102
|
__privateAdd(this, _client, null);
|
|
@@ -164,16 +163,16 @@ class InitTracker {
|
|
|
164
163
|
return this._identifyEvent(userId, intercomHash);
|
|
165
164
|
}
|
|
166
165
|
trackDownloadLibrary(library) {
|
|
167
|
-
return this._trackEvent(
|
|
166
|
+
return this._trackEvent(EventType.DownloadLibrary, { library });
|
|
168
167
|
}
|
|
169
168
|
trackInitIdentify() {
|
|
170
|
-
return this._trackEvent(
|
|
169
|
+
return this._trackEvent(EventType.InitIdentify);
|
|
171
170
|
}
|
|
172
171
|
trackInitStart(repoDomain) {
|
|
173
|
-
return this._trackEvent(
|
|
172
|
+
return this._trackEvent(EventType.InitStart, { repo: repoDomain });
|
|
174
173
|
}
|
|
175
174
|
trackInitDone(framework) {
|
|
176
|
-
return this._trackEvent(
|
|
175
|
+
return this._trackEvent(EventType.InitDone, { framework });
|
|
177
176
|
}
|
|
178
177
|
}
|
|
179
178
|
_client = new WeakMap();
|
|
@@ -231,7 +230,7 @@ const logs = /*#__PURE__*/Object.freeze({
|
|
|
231
230
|
});
|
|
232
231
|
|
|
233
232
|
const { Cookie } = core.Utils;
|
|
234
|
-
const { DEFAULT_BASE
|
|
233
|
+
const { DEFAULT_BASE, DEFAULT_SERVER_PORT } = core.CONSTS;
|
|
235
234
|
const { bold, underline, spinner, writeError } = logs;
|
|
236
235
|
const isHandlerData = (data) => {
|
|
237
236
|
if (typeof data != "object")
|
|
@@ -274,13 +273,16 @@ const authenticationHandler = (server) => (onSuccess, onFail) => {
|
|
|
274
273
|
}
|
|
275
274
|
};
|
|
276
275
|
};
|
|
276
|
+
function stripTrailingSlash(str) {
|
|
277
|
+
return str.endsWith("/") ? str.slice(0, -1) : str;
|
|
278
|
+
}
|
|
277
279
|
function buildServer(base, port, host) {
|
|
278
280
|
const server = hapi__namespace.server({
|
|
279
281
|
port,
|
|
280
282
|
host,
|
|
281
283
|
routes: {
|
|
282
284
|
cors: {
|
|
283
|
-
origin: [base],
|
|
285
|
+
origin: [stripTrailingSlash(base)],
|
|
284
286
|
headers: ["Origin", "X-Requested-With", "Content-Type", "Accept"]
|
|
285
287
|
}
|
|
286
288
|
}
|
|
@@ -303,7 +305,7 @@ function askSingleChar(title) {
|
|
|
303
305
|
process.stdin.on("data", handler);
|
|
304
306
|
});
|
|
305
307
|
}
|
|
306
|
-
async function startServerAndOpenBrowser(url, action, base = DEFAULT_BASE
|
|
308
|
+
async function startServerAndOpenBrowser(url, action, base = DEFAULT_BASE, port = DEFAULT_SERVER_PORT) {
|
|
307
309
|
const confirmation = await askSingleChar(`>> Press any key to open the browser to ${action} or q to exit:`);
|
|
308
310
|
if (confirmation === "q" || confirmation === "")
|
|
309
311
|
return process.exit(-1);
|
|
@@ -340,46 +342,92 @@ async function startServerAndOpenBrowser(url, action, base = DEFAULT_BASE$1, por
|
|
|
340
342
|
}
|
|
341
343
|
|
|
342
344
|
async function startAuth({
|
|
343
|
-
|
|
345
|
+
client,
|
|
344
346
|
url,
|
|
345
347
|
action
|
|
346
348
|
}) {
|
|
347
|
-
const { onLoginFail } = await startServerAndOpenBrowser(url, action,
|
|
349
|
+
const { onLoginFail } = await startServerAndOpenBrowser(url, action, client.apisEndpoints.Wroom);
|
|
348
350
|
try {
|
|
349
|
-
await core.Utils.Poll.startPolling(() => Auth.validateSession(
|
|
351
|
+
await core.Utils.Poll.startPolling(() => Auth.validateSession(client), (isSessionValid) => isSessionValid == true, 3e3, 60);
|
|
350
352
|
return;
|
|
351
353
|
} catch (e) {
|
|
352
354
|
onLoginFail();
|
|
353
355
|
}
|
|
354
356
|
}
|
|
355
357
|
const Auth = {
|
|
356
|
-
login: async (
|
|
357
|
-
const endpoints = Prismic.Endpoints.buildEndpoints(
|
|
358
|
+
login: async (client) => {
|
|
359
|
+
const endpoints = Prismic.Endpoints.buildEndpoints(client.apisEndpoints.Wroom);
|
|
358
360
|
return startAuth({
|
|
359
|
-
|
|
361
|
+
client,
|
|
360
362
|
url: endpoints.Dashboard.cliLogin,
|
|
361
363
|
action: "login"
|
|
362
364
|
});
|
|
363
365
|
},
|
|
364
|
-
|
|
365
|
-
const
|
|
366
|
-
return
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
validateSession: async (requiredBase) => {
|
|
374
|
-
const config = Prismic.PrismicSharedConfigManager.get();
|
|
375
|
-
if (!config.cookies.length)
|
|
376
|
-
return Promise.resolve(null);
|
|
377
|
-
if (requiredBase != config.base)
|
|
378
|
-
return Promise.resolve(null);
|
|
379
|
-
return Prismic.Communication.validateSession(config.cookies, requiredBase).catch(() => null);
|
|
366
|
+
validateSession: async (client) => {
|
|
367
|
+
const authToken = Prismic.PrismicSharedConfigManager.getAuth();
|
|
368
|
+
return client.updateAuthenticationToken(authToken).profile().then((userProfile) => {
|
|
369
|
+
Prismic.PrismicSharedConfigManager.setProperties({
|
|
370
|
+
shortId: userProfile.shortId,
|
|
371
|
+
intercomHash: userProfile.intercomHash
|
|
372
|
+
});
|
|
373
|
+
return true;
|
|
374
|
+
}).catch(() => false);
|
|
380
375
|
}
|
|
381
376
|
};
|
|
382
377
|
|
|
378
|
+
class InitClient extends client.Client {
|
|
379
|
+
async listRepositories() {
|
|
380
|
+
return client.getAndValidateResponse(this._get(`${this.apisEndpoints.Users}repositories`), "repository list", t__namespace.array(core.Models.Repository));
|
|
381
|
+
}
|
|
382
|
+
async createRepository(domain, framework) {
|
|
383
|
+
const data = {
|
|
384
|
+
domain,
|
|
385
|
+
framework,
|
|
386
|
+
plan: "personal",
|
|
387
|
+
isAnnual: "false",
|
|
388
|
+
role: "developer"
|
|
389
|
+
};
|
|
390
|
+
return this._fetch({
|
|
391
|
+
method: "post",
|
|
392
|
+
url: `${this.apisEndpoints.Wroom}authentication/newrepository?app=slicemachine`,
|
|
393
|
+
data,
|
|
394
|
+
headers: {
|
|
395
|
+
Cookie: Prismic.PrismicSharedConfigManager.get().cookies,
|
|
396
|
+
"User-Agent": "prismic-cli/sm"
|
|
397
|
+
}
|
|
398
|
+
}).then(() => domain);
|
|
399
|
+
}
|
|
400
|
+
async domainExist(domain) {
|
|
401
|
+
return client.getAndValidateResponse(this._get(`${this.apisEndpoints.Wroom}app/dashboard/repositories/${domain}/exists`), "repository exists", t__namespace.boolean);
|
|
402
|
+
}
|
|
403
|
+
async pushDocuments(signature, documents, cookies) {
|
|
404
|
+
if (!this.repository)
|
|
405
|
+
throw new Error("Repository undefined in the client");
|
|
406
|
+
const repositoryDirectUrl = new URL(this.apisEndpoints.Wroom);
|
|
407
|
+
repositoryDirectUrl.hostname = `${this.repository}.${repositoryDirectUrl.hostname}`;
|
|
408
|
+
return this._fetch({
|
|
409
|
+
method: "post",
|
|
410
|
+
url: `${repositoryDirectUrl.toString()}starter/documents`,
|
|
411
|
+
data: { signature, documents: JSON.stringify(documents) },
|
|
412
|
+
headers: {
|
|
413
|
+
Cookie: cookies,
|
|
414
|
+
"User-Agent": "prismic-cli/0"
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async function lsdir(dir) {
|
|
421
|
+
return fs__default["default"].promises.readdir(dir).then((dirs) => {
|
|
422
|
+
return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isDirectory()).map((subdirectory) => path__default["default"].join(dir, subdirectory));
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
async function lsfiles(dir) {
|
|
426
|
+
return fs__default["default"].promises.readdir(dir).then((dirs) => {
|
|
427
|
+
return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isFile()).map((file) => path__default["default"].join(dir, file));
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
|
|
383
431
|
function findArgument(args, name) {
|
|
384
432
|
const flagIndex = args.indexOf(`--${name}`);
|
|
385
433
|
if (flagIndex === -1)
|
|
@@ -396,6 +444,16 @@ function findFlag(args, name) {
|
|
|
396
444
|
return args.includes(toFind);
|
|
397
445
|
}
|
|
398
446
|
const execCommand = util__default["default"].promisify(child_process.exec);
|
|
447
|
+
function getApplicationMode(argumentValue) {
|
|
448
|
+
switch (argumentValue) {
|
|
449
|
+
case client.ApplicationMode.PROD:
|
|
450
|
+
case client.ApplicationMode.STAGE:
|
|
451
|
+
case client.ApplicationMode.DEV:
|
|
452
|
+
return argumentValue;
|
|
453
|
+
default:
|
|
454
|
+
return null;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
399
457
|
|
|
400
458
|
const {
|
|
401
459
|
PRISMIC_CLIENT,
|
|
@@ -465,16 +523,15 @@ function validatePkg(cwd) {
|
|
|
465
523
|
}
|
|
466
524
|
}
|
|
467
525
|
|
|
468
|
-
function createRepository(domain, framework
|
|
526
|
+
function createRepository(client, domain, framework) {
|
|
469
527
|
const spinner = spinner$1("Creating Prismic Repository");
|
|
470
528
|
spinner.start();
|
|
471
|
-
return
|
|
472
|
-
const addressUrl = new URL(
|
|
473
|
-
|
|
474
|
-
addressUrl.hostname = `${repoDomainName}.${addressUrl.hostname}`;
|
|
529
|
+
return client.createRepository(domain, framework).then((domain2) => {
|
|
530
|
+
const addressUrl = new URL(client.apisEndpoints.Wroom);
|
|
531
|
+
addressUrl.hostname = `${domain2}.${addressUrl.hostname}`;
|
|
475
532
|
const address = addressUrl.toString();
|
|
476
533
|
spinner.succeed(`We created your new repository ${address}`);
|
|
477
|
-
return
|
|
534
|
+
return domain2;
|
|
478
535
|
}).catch((error) => {
|
|
479
536
|
spinner.fail(`Error creating repository ${domain}`);
|
|
480
537
|
if (error.message) {
|
|
@@ -486,14 +543,38 @@ function createRepository(domain, framework, cookies, base) {
|
|
|
486
543
|
});
|
|
487
544
|
}
|
|
488
545
|
|
|
546
|
+
async function validateRepositoryName(client, name) {
|
|
547
|
+
const domain = name.trim();
|
|
548
|
+
const errors = [];
|
|
549
|
+
const startsWithLetter = /^[a-zA-Z]/.test(domain);
|
|
550
|
+
if (!startsWithLetter)
|
|
551
|
+
errors.push("Must start with a letter.");
|
|
552
|
+
const acceptedChars = /^[a-z0-9-]+$/.test(domain);
|
|
553
|
+
if (!acceptedChars)
|
|
554
|
+
errors.push("Must contain only lowercase letters, numbers and hyphens.");
|
|
555
|
+
const fourCharactersOrMore = domain.length >= 4;
|
|
556
|
+
if (!fourCharactersOrMore)
|
|
557
|
+
errors.push("Must have four or more alphanumeric characters and/or hyphens.");
|
|
558
|
+
const endsWithALetterOrNumber = /[a-z0-9]$/.test(domain);
|
|
559
|
+
if (!endsWithALetterOrNumber)
|
|
560
|
+
errors.push("Must end in a letter or a number.");
|
|
561
|
+
const thirtyCharacterOrLess = domain.length <= 30;
|
|
562
|
+
if (!thirtyCharacterOrLess)
|
|
563
|
+
errors.push("Must be 30 characters or less");
|
|
564
|
+
if (errors.length > 0) {
|
|
565
|
+
const errorString = errors.map((d, i) => `(${i + 1}: ${d}`).join(" ");
|
|
566
|
+
const msg = `Validation errors: ${errorString}`;
|
|
567
|
+
return Promise.reject(new Error(msg));
|
|
568
|
+
}
|
|
569
|
+
return client.domainExist(domain).then((isAvailable) => isAvailable ? true : Promise.reject(new Error(`${name} is already in use`))).catch(() => Promise.reject(new Error(`${name} is already in use`)));
|
|
570
|
+
}
|
|
571
|
+
|
|
489
572
|
const CREATE_REPO = "$_CREATE_REPO";
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
const repoName = value ? cyan(value) : dim.cyan("repo-name");
|
|
493
|
-
return `${cyan.dim(`${address.protocol}//`)}${repoName}${cyan.dim(`.${address.hostname}`)}`;
|
|
573
|
+
function prettyRepoName(address, domain) {
|
|
574
|
+
return `${cyan.dim(`${address.protocol}//`)}${cyan(domain)}${cyan.dim(`.${address.hostname}`)}`;
|
|
494
575
|
}
|
|
495
|
-
async function promptForRepoDomain(
|
|
496
|
-
const address = new URL(
|
|
576
|
+
async function promptForRepoDomain(client, defaultValue) {
|
|
577
|
+
const address = new URL(client.apisEndpoints.Wroom);
|
|
497
578
|
writeInfo("The name acts as a domain/endpoint for your content repo and should be completely unique.");
|
|
498
579
|
return inquirer__namespace.prompt([
|
|
499
580
|
{
|
|
@@ -502,11 +583,8 @@ async function promptForRepoDomain(base, defaultValue) {
|
|
|
502
583
|
type: "input",
|
|
503
584
|
required: true,
|
|
504
585
|
default: defaultValue,
|
|
505
|
-
transformer: (value) => prettyRepoName(address, value || defaultValue),
|
|
506
|
-
|
|
507
|
-
const result = await Prismic__namespace.Communication.validateRepositoryName(name, base, false);
|
|
508
|
-
return result === name || result;
|
|
509
|
-
}
|
|
586
|
+
transformer: (value) => prettyRepoName(address, value || defaultValue || "repository"),
|
|
587
|
+
validate: (name) => validateRepositoryName(client, name)
|
|
510
588
|
}
|
|
511
589
|
]).then((res) => res.repoDomain);
|
|
512
590
|
}
|
|
@@ -560,26 +638,26 @@ function sortReposForPrompt(repos, base, cwd) {
|
|
|
560
638
|
createNew
|
|
561
639
|
]).sort(orderPrompts(maybeConfiguredRepoName));
|
|
562
640
|
}
|
|
563
|
-
async function chooseOrCreateARepository(cwd, framework,
|
|
564
|
-
const
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
return
|
|
641
|
+
async function chooseOrCreateARepository(client, cwd, framework, preSelectedRepository) {
|
|
642
|
+
const repositories = await client.listRepositories();
|
|
643
|
+
const isPreSelectedValid = preSelectedRepository && repositories.find((repository) => repository.domain === preSelectedRepository);
|
|
644
|
+
if (isPreSelectedValid)
|
|
645
|
+
return preSelectedRepository;
|
|
646
|
+
if (repositories.length === 0) {
|
|
647
|
+
const domainName = await promptForRepoDomain(client, preSelectedRepository);
|
|
648
|
+
await createRepository(client, domainName, framework);
|
|
649
|
+
return domainName;
|
|
572
650
|
}
|
|
573
|
-
const choices = sortReposForPrompt(
|
|
651
|
+
const choices = sortReposForPrompt(repositories, client.apisEndpoints.Wroom, cwd);
|
|
574
652
|
const numberOfDisabledRepos = choices.filter((repo) => {
|
|
575
653
|
if (repo instanceof Separator__default["default"])
|
|
576
654
|
return false;
|
|
577
655
|
return repo.disabled;
|
|
578
656
|
}).length;
|
|
579
|
-
const
|
|
657
|
+
const promptResult = await inquirer__namespace.prompt([
|
|
580
658
|
{
|
|
581
659
|
type: "list",
|
|
582
|
-
name: "
|
|
660
|
+
name: "chosenRepository",
|
|
583
661
|
default: 0,
|
|
584
662
|
required: true,
|
|
585
663
|
message: "Connect a Prismic Repository or create a new one",
|
|
@@ -587,11 +665,12 @@ async function chooseOrCreateARepository(cwd, framework, cookies, base = DEFAULT
|
|
|
587
665
|
pageSize: numberOfDisabledRepos + 2 <= 7 ? 7 : numberOfDisabledRepos + 2
|
|
588
666
|
}
|
|
589
667
|
]);
|
|
590
|
-
if (
|
|
591
|
-
const domainName = await promptForRepoDomain(
|
|
592
|
-
|
|
668
|
+
if (promptResult.chosenRepository === CREATE_REPO) {
|
|
669
|
+
const domainName = await promptForRepoDomain(client, preSelectedRepository);
|
|
670
|
+
await createRepository(client, domainName, framework);
|
|
671
|
+
return domainName;
|
|
593
672
|
}
|
|
594
|
-
return
|
|
673
|
+
return promptResult.chosenRepository;
|
|
595
674
|
}
|
|
596
675
|
|
|
597
676
|
async function promptForFramework() {
|
|
@@ -652,56 +731,21 @@ async function detectFramework(cwd) {
|
|
|
652
731
|
}
|
|
653
732
|
}
|
|
654
733
|
|
|
655
|
-
async function
|
|
656
|
-
const
|
|
657
|
-
const url = new URL(userServiceBase);
|
|
658
|
-
url.pathname = "profile";
|
|
659
|
-
const endpoint = url.toString();
|
|
660
|
-
const token = core.Utils.Cookie.parsePrismicAuthToken(cookies);
|
|
661
|
-
return axios__default["default"].get(endpoint, {
|
|
662
|
-
headers: {
|
|
663
|
-
Authorization: `Bearer ${token}`
|
|
664
|
-
}
|
|
665
|
-
}).then((res) => _function.pipe(core.Models.UserProfile.decode(res.data), Either.fold(() => {
|
|
666
|
-
throw new Error("Can't parse user profile");
|
|
667
|
-
}, (data) => data)));
|
|
668
|
-
}
|
|
669
|
-
async function validateSessionAndGetProfile(base = core.CONSTS.DEFAULT_BASE) {
|
|
670
|
-
const config = Prismic__namespace.PrismicSharedConfigManager.get();
|
|
671
|
-
if (!config.cookies.length)
|
|
672
|
-
return Promise.resolve(null);
|
|
673
|
-
if (base != config.base)
|
|
674
|
-
return Promise.resolve(null);
|
|
675
|
-
try {
|
|
676
|
-
const info = await Prismic__namespace.Communication.validateSession(config.cookies, base);
|
|
677
|
-
const profile = await getUserProfile(config.cookies, base).catch(() => null);
|
|
678
|
-
if (profile == null ? void 0 : profile.shortId) {
|
|
679
|
-
Prismic__namespace.PrismicSharedConfigManager.setProperties({
|
|
680
|
-
shortId: profile.shortId,
|
|
681
|
-
intercomHash: profile.intercomHash
|
|
682
|
-
});
|
|
683
|
-
}
|
|
684
|
-
return { info, profile };
|
|
685
|
-
} catch (e) {
|
|
686
|
-
return null;
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
async function loginOrBypass(base) {
|
|
691
|
-
const user = await validateSessionAndGetProfile(base).catch((err) => console.log(err));
|
|
734
|
+
async function loginOrBypass(client) {
|
|
735
|
+
const user = await client.profile().catch(() => null);
|
|
692
736
|
if (user) {
|
|
693
|
-
const email = user.
|
|
737
|
+
const email = user.email;
|
|
694
738
|
writeCheck(`Logged in as ${bold$1(email)}`);
|
|
695
739
|
return user;
|
|
696
|
-
} else {
|
|
697
|
-
await Auth.login(base);
|
|
698
|
-
const user2 = await validateSessionAndGetProfile(base);
|
|
699
|
-
return user2;
|
|
700
740
|
}
|
|
741
|
+
await Auth.login(client);
|
|
742
|
+
client.updateAuthenticationToken(Prismic.PrismicSharedConfigManager.getAuth());
|
|
743
|
+
const userAfterLogin = await client.profile();
|
|
744
|
+
return userAfterLogin;
|
|
701
745
|
}
|
|
702
746
|
|
|
703
747
|
const defaultSliceMachineVersion = "0.0.41";
|
|
704
|
-
async function configureProject(
|
|
748
|
+
async function configureProject(client, cwd, repositoryDomainName, framework, sliceLibPath = [], tracking = true) {
|
|
705
749
|
const frameworkName = NodeUtils__namespace.Framework.fancyName(framework.value);
|
|
706
750
|
const spinner = spinner$1(`Configuring your ${frameworkName} and Prismic project...`);
|
|
707
751
|
spinner.start();
|
|
@@ -713,7 +757,7 @@ async function configureProject(cwd, base, repositoryDomainName, framework, slic
|
|
|
713
757
|
const libs = manifest.content && manifest.content.libraries && manifest.content.libraries.length > 0 ? manifest.content.libraries : ["@/slices"];
|
|
714
758
|
const manifestUpdated = {
|
|
715
759
|
...manifestAlreadyExistWithContent ? manifest.content : { _latest: sliceMachineVersionInstalled },
|
|
716
|
-
apiEndpoint: Prismic__namespace.Endpoints.buildRepositoryEndpoint(
|
|
760
|
+
apiEndpoint: Prismic__namespace.Endpoints.buildRepositoryEndpoint(client.apisEndpoints.Wroom, repositoryDomainName),
|
|
717
761
|
libraries: [...libs, ...sliceLibPath],
|
|
718
762
|
...framework.manuallyAdded ? { framework: framework.value } : {},
|
|
719
763
|
...!tracking ? { tracking } : {}
|
|
@@ -878,100 +922,6 @@ async function installLib(cwd, libGithubPath, branch = "HEAD") {
|
|
|
878
922
|
}
|
|
879
923
|
}
|
|
880
924
|
|
|
881
|
-
function handleErrors(prefix, err) {
|
|
882
|
-
if (axios__default["default"].isAxiosError(err) && err.response) {
|
|
883
|
-
writeError$1(`${prefix} | [${err.response.status}]: ${err.response.statusText}`);
|
|
884
|
-
} else if (err instanceof Error) {
|
|
885
|
-
writeError$1(`${prefix} ${err.message}`);
|
|
886
|
-
} else {
|
|
887
|
-
writeError$1(`${prefix} ${String(err)}`);
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
async function getRemoteSliceIds(customTypeApiEndpoint, repository, authorization) {
|
|
891
|
-
const addr = `${stripLastSlash(customTypeApiEndpoint)}/slices`;
|
|
892
|
-
return axios__default["default"].get(addr, {
|
|
893
|
-
headers: {
|
|
894
|
-
Authorization: `Bearer ${authorization}`,
|
|
895
|
-
repository
|
|
896
|
-
}
|
|
897
|
-
}).then((res) => {
|
|
898
|
-
return Array.isArray(res.data) ? res.data.map((model) => model.id) : [];
|
|
899
|
-
});
|
|
900
|
-
}
|
|
901
|
-
async function sendModelToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, model) {
|
|
902
|
-
const data = models.Slices.fromSM(model);
|
|
903
|
-
const updateOrInsertUrl = `${customTypesApiEndpoint}slices/${remoteSliceIds.includes(model.id) ? "update" : "insert"}`;
|
|
904
|
-
return axios__default["default"].post(updateOrInsertUrl, data, {
|
|
905
|
-
headers: {
|
|
906
|
-
Authorization: `Bearer ${authorization}`,
|
|
907
|
-
repository
|
|
908
|
-
}
|
|
909
|
-
}).then(() => {
|
|
910
|
-
return;
|
|
911
|
-
}).catch((err) => {
|
|
912
|
-
handleErrors(`sending slice ${model.id}, please try again. If the problem persists, contact us.`, err);
|
|
913
|
-
throw err;
|
|
914
|
-
});
|
|
915
|
-
}
|
|
916
|
-
async function sendManyModelsToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, models) {
|
|
917
|
-
return Promise.all(models.map((model) => sendModelToPrismic(repository, authorization, customTypesApiEndpoint, remoteSliceIds, model))).then(() => {
|
|
918
|
-
return;
|
|
919
|
-
}).catch(() => {
|
|
920
|
-
process.exit(1);
|
|
921
|
-
});
|
|
922
|
-
}
|
|
923
|
-
function stripLastSlash(str) {
|
|
924
|
-
return str.replace(/\/*$/g, "");
|
|
925
|
-
}
|
|
926
|
-
function getRemoteCustomTypeIds(customTypeApiEndpoint, repository, authorization) {
|
|
927
|
-
const addr = `${stripLastSlash(customTypeApiEndpoint)}/customtypes`;
|
|
928
|
-
return axios__default["default"].get(addr, {
|
|
929
|
-
headers: {
|
|
930
|
-
Authorization: `Bearer ${authorization}`,
|
|
931
|
-
repository
|
|
932
|
-
}
|
|
933
|
-
}).then((res) => {
|
|
934
|
-
return Array.isArray(res.data) ? res.data.map((ct) => ct.id) : [];
|
|
935
|
-
});
|
|
936
|
-
}
|
|
937
|
-
async function sendCustomTypeToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customType) {
|
|
938
|
-
const shouldUpdate = remoteCustomTypeIds.includes(customType.id);
|
|
939
|
-
const addr = `${stripLastSlash(customTypeApiEndpoint)}/customtypes/${shouldUpdate ? "update" : "insert"}`;
|
|
940
|
-
return axios__default["default"].post(addr, customType, {
|
|
941
|
-
headers: {
|
|
942
|
-
repository,
|
|
943
|
-
Authorization: `Bearer ${authorization}`
|
|
944
|
-
}
|
|
945
|
-
}).then(() => {
|
|
946
|
-
return;
|
|
947
|
-
}).catch((err) => {
|
|
948
|
-
handleErrors(`sending custom type ${customType.id}, please try again. If the problem persists, contact us.`, err);
|
|
949
|
-
throw err;
|
|
950
|
-
});
|
|
951
|
-
}
|
|
952
|
-
async function sendManyCustomTypesToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customTypes) {
|
|
953
|
-
return Promise.all(customTypes.map((customType) => sendCustomTypeToPrismic(repository, authorization, customTypeApiEndpoint, remoteCustomTypeIds, customType))).then(() => {
|
|
954
|
-
return;
|
|
955
|
-
}).catch(() => {
|
|
956
|
-
process.exit(1);
|
|
957
|
-
});
|
|
958
|
-
}
|
|
959
|
-
|
|
960
|
-
const ProductionApisEndpoints = {
|
|
961
|
-
Models: "https://customtypes.prismic.io/",
|
|
962
|
-
AclProvider: "https://0yyeb2g040.execute-api.us-east-1.amazonaws.com/prod/"
|
|
963
|
-
};
|
|
964
|
-
const StageApisEndpoints = {
|
|
965
|
-
Models: "https://customtypes.wroom.io/",
|
|
966
|
-
AclProvider: "https://2iamcvnxf4.execute-api.us-east-1.amazonaws.com/stage/"
|
|
967
|
-
};
|
|
968
|
-
const getEndpointsFromBase = (base) => {
|
|
969
|
-
const url = new URL(base);
|
|
970
|
-
if (url.hostname === "wroom.io")
|
|
971
|
-
return StageApisEndpoints;
|
|
972
|
-
return ProductionApisEndpoints;
|
|
973
|
-
};
|
|
974
|
-
|
|
975
925
|
async function promptToPushSlices() {
|
|
976
926
|
return inquirer__default["default"].prompt([
|
|
977
927
|
{
|
|
@@ -988,127 +938,80 @@ async function promptToPushCustomTypes() {
|
|
|
988
938
|
type: "confirm",
|
|
989
939
|
name: "pushCustomTypes",
|
|
990
940
|
default: false,
|
|
991
|
-
message: "Your repository already contains Custom Types. Do you want to continue pushing your local
|
|
941
|
+
message: "Your repository already contains Custom Types. Do you want to continue pushing your local Custom Types?"
|
|
992
942
|
}
|
|
993
943
|
]).then((res) => res.pushCustomTypes);
|
|
994
944
|
}
|
|
995
945
|
|
|
996
|
-
async function
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
return fs__default["default"].promises.readFile(filePath).then((file) => {
|
|
1014
|
-
form.append("file", file, { filename });
|
|
1015
|
-
return form;
|
|
1016
|
-
}).catch(() => {
|
|
1017
|
-
writeError$1(`Error reading preview image: ${filename}`);
|
|
1018
|
-
return null;
|
|
1019
|
-
});
|
|
1020
|
-
}
|
|
1021
|
-
function createS3Key(repository, sliceName, variationId, filename) {
|
|
1022
|
-
return `${repository}/shared-slices/${snakeCase__default["default"](sliceName)}/${snakeCase__default["default"](variationId)}-${uniqid__default["default"]()}/${filename}`;
|
|
1023
|
-
}
|
|
1024
|
-
async function sendVariationPreviewToS3(acl, repository, sliceName, variationId, filePath) {
|
|
1025
|
-
const filename = path__default["default"].basename(filePath);
|
|
1026
|
-
const key = createS3Key(repository, sliceName, variationId, filename);
|
|
1027
|
-
const form = await createFormForS3(key, filename, filePath, acl);
|
|
1028
|
-
if (form === null)
|
|
1029
|
-
return null;
|
|
1030
|
-
if (form.hasKnownLength() === false) {
|
|
1031
|
-
writeError$1(`[slice/push] An error occurred while uploading preview image ${filePath} as length in unknown`);
|
|
1032
|
-
}
|
|
1033
|
-
const errorMessage = `[slice/push] An error occurred while uploading preview images for ${sliceName}-${variationId} - please contact support`;
|
|
1034
|
-
return axios__default["default"].post(acl.values.url, form, {
|
|
1035
|
-
headers: {
|
|
1036
|
-
...form.getHeaders(),
|
|
1037
|
-
"Content-Length": String(form.getLengthSync())
|
|
1038
|
-
}
|
|
1039
|
-
}).then((res) => {
|
|
1040
|
-
if (res.status !== 204) {
|
|
1041
|
-
writeError$1(errorMessage);
|
|
1042
|
-
writeError$1(`${res.status}: ${res.statusText}`);
|
|
1043
|
-
return null;
|
|
1044
|
-
} else {
|
|
1045
|
-
return `${acl.imgixEndpoint}/${key}`;
|
|
1046
|
-
}
|
|
1047
|
-
}).catch((err) => {
|
|
1048
|
-
writeError$1(errorMessage);
|
|
1049
|
-
if (axios__default["default"].isAxiosError(err) && err.response) {
|
|
1050
|
-
writeError$1(`${err.response.status}: ${err.response.statusText}`);
|
|
1051
|
-
} else if (err instanceof Error) {
|
|
1052
|
-
writeError$1(err.message);
|
|
1053
|
-
} else {
|
|
1054
|
-
writeError$1(String(err));
|
|
1055
|
-
}
|
|
1056
|
-
return null;
|
|
1057
|
-
});
|
|
1058
|
-
}
|
|
1059
|
-
async function maybeAddImageUrlToVariation(acl, repository, modelId, pathToScreenShot, variation) {
|
|
1060
|
-
const imageUrl = await sendVariationPreviewToS3(acl, repository, modelId, variation.id, pathToScreenShot);
|
|
1061
|
-
if (!imageUrl)
|
|
946
|
+
async function updateVariationWithScreenshot(client, acl, screenshotPaths, sliceName, variation) {
|
|
947
|
+
const screenshot = screenshotPaths[variation.id];
|
|
948
|
+
if (!screenshot || !screenshot.path)
|
|
949
|
+
return Promise.resolve(variation);
|
|
950
|
+
return client.uploadScreenshot({
|
|
951
|
+
acl,
|
|
952
|
+
sliceName,
|
|
953
|
+
variationId: variation.id,
|
|
954
|
+
filePath: screenshot.path
|
|
955
|
+
}).then((screenshotUrl) => {
|
|
956
|
+
return {
|
|
957
|
+
...variation,
|
|
958
|
+
imageUrl: screenshotUrl
|
|
959
|
+
};
|
|
960
|
+
}).catch((error) => {
|
|
961
|
+
writeError$1(`Couldn't upload screenshot slice: ${sliceName} - variation: ${variation.id}`);
|
|
962
|
+
writeError$1(error.message, "Full error:");
|
|
1062
963
|
return variation;
|
|
1063
|
-
|
|
1064
|
-
...variation,
|
|
1065
|
-
imageUrl
|
|
1066
|
-
};
|
|
964
|
+
});
|
|
1067
965
|
}
|
|
1068
|
-
async function
|
|
1069
|
-
return Promise.all(
|
|
1070
|
-
const
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
966
|
+
async function updateSlicesWithScreenshots(client, acl, components) {
|
|
967
|
+
return Promise.all(components.map(async (component) => {
|
|
968
|
+
const { screenshotPaths, model } = component;
|
|
969
|
+
const variationsUpdated = await Promise.all(model.variations.map(async (variation) => updateVariationWithScreenshot(client, acl, screenshotPaths, model.id, variation)));
|
|
970
|
+
return {
|
|
971
|
+
...model,
|
|
972
|
+
variations: variationsUpdated
|
|
973
|
+
};
|
|
1074
974
|
}));
|
|
1075
975
|
}
|
|
1076
|
-
async function maybeUpdateModelVariationsWithImageUrl(acl, repository, component) {
|
|
1077
|
-
const { screenshotPaths, model } = component;
|
|
1078
|
-
const variations = await addImageUrlsToVariations(acl, repository, model.id, screenshotPaths, model.variations);
|
|
1079
|
-
return {
|
|
1080
|
-
...model,
|
|
1081
|
-
variations
|
|
1082
|
-
};
|
|
1083
|
-
}
|
|
1084
|
-
async function addImageUrlsToModelVariations(acl, repository, components) {
|
|
1085
|
-
return Promise.all(components.map(async (component) => maybeUpdateModelVariationsWithImageUrl(acl, repository, component)));
|
|
1086
|
-
}
|
|
1087
976
|
|
|
1088
|
-
async function
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
977
|
+
async function sendSlices(client, cwd, manifest) {
|
|
978
|
+
if (!manifest.libraries)
|
|
979
|
+
return Promise.resolve(false);
|
|
980
|
+
const libraries = Libraries__namespace.libraries(cwd, manifest.libraries);
|
|
981
|
+
const components = libraries.reduce((acc, lib) => {
|
|
982
|
+
return [...acc, ...lib.components];
|
|
983
|
+
}, []);
|
|
984
|
+
if (components.length === 0)
|
|
1092
985
|
return Promise.resolve(false);
|
|
1093
|
-
const
|
|
1094
|
-
if (
|
|
986
|
+
const remoteSlicesIds = await client.getSlices().then((slices) => slices.map((slice) => slice.id));
|
|
987
|
+
if (remoteSlicesIds.length) {
|
|
1095
988
|
const pushAnyway = await promptToPushSlices();
|
|
1096
989
|
if (pushAnyway === false)
|
|
1097
990
|
return Promise.resolve(true);
|
|
1098
991
|
}
|
|
1099
992
|
const spinner = spinner$1("Pushing existing Slice models to your repository");
|
|
1100
993
|
spinner.start();
|
|
1101
|
-
const acl = await createAcl(
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
await
|
|
994
|
+
const acl = await client.createAcl().catch((error) => {
|
|
995
|
+
writeError$1("Uploading screenshots for your slices failed, please contact us.");
|
|
996
|
+
writeError$1(error.message, "Full error:");
|
|
997
|
+
return null;
|
|
998
|
+
});
|
|
999
|
+
const models$1 = acl ? await updateSlicesWithScreenshots(client, acl, components) : components.map((component) => component.model);
|
|
1000
|
+
await Promise.all(models$1.map(async (model) => {
|
|
1001
|
+
const slice = models.Slices.fromSM(model);
|
|
1002
|
+
const promise = remoteSlicesIds.includes(slice.id) ? client.updateSlice(slice) : client.insertSlice(slice);
|
|
1003
|
+
return promise.catch((error) => {
|
|
1004
|
+
writeError$1(`Sending slice ${model.id} - ${error.message}`);
|
|
1005
|
+
throw error;
|
|
1006
|
+
});
|
|
1007
|
+
})).catch(() => {
|
|
1008
|
+
process.exit(1);
|
|
1009
|
+
});
|
|
1107
1010
|
spinner.succeed();
|
|
1108
1011
|
return Promise.resolve(true);
|
|
1109
1012
|
}
|
|
1110
1013
|
|
|
1111
|
-
function
|
|
1014
|
+
function readLocalCustomTypes(cwd) {
|
|
1112
1015
|
const customTypePaths = NodeUtils.CustomTypesPaths(cwd);
|
|
1113
1016
|
const dir = customTypePaths.value();
|
|
1114
1017
|
if (NodeUtils.Files.isDirectory(dir) === false)
|
|
@@ -1132,12 +1035,11 @@ function readCustomTypes(cwd) {
|
|
|
1132
1035
|
}, []);
|
|
1133
1036
|
return files;
|
|
1134
1037
|
}
|
|
1135
|
-
async function
|
|
1136
|
-
const
|
|
1137
|
-
|
|
1138
|
-
if (customTypes.length === 0)
|
|
1038
|
+
async function sendCustomTypes(client, cwd) {
|
|
1039
|
+
const localCustomTypes = readLocalCustomTypes(cwd);
|
|
1040
|
+
if (localCustomTypes.length === 0)
|
|
1139
1041
|
return Promise.resolve(false);
|
|
1140
|
-
const remoteCustomTypeIds = await
|
|
1042
|
+
const remoteCustomTypeIds = await client.getCustomTypes().then((customTypes) => customTypes.map((customType) => customType.id));
|
|
1141
1043
|
if (remoteCustomTypeIds.length) {
|
|
1142
1044
|
const shouldPush = await promptToPushCustomTypes();
|
|
1143
1045
|
if (shouldPush === false)
|
|
@@ -1145,7 +1047,15 @@ async function sendCustomTypesFromStarter(repository, authorization, base, cwd)
|
|
|
1145
1047
|
}
|
|
1146
1048
|
const spinner = spinner$1("Pushing existing custom types to your repository");
|
|
1147
1049
|
spinner.start();
|
|
1148
|
-
await
|
|
1050
|
+
await Promise.all(localCustomTypes.map(async (customType) => {
|
|
1051
|
+
const promise = remoteCustomTypeIds.includes(customType.id) ? client.updateCustomType(customType) : client.insertCustomType(customType);
|
|
1052
|
+
return promise.catch((error) => {
|
|
1053
|
+
writeError$1(`Sending custom type ${customType.id} - ${error.message}`);
|
|
1054
|
+
throw error;
|
|
1055
|
+
});
|
|
1056
|
+
})).catch(() => {
|
|
1057
|
+
process.exit(1);
|
|
1058
|
+
});
|
|
1149
1059
|
spinner.succeed();
|
|
1150
1060
|
return Promise.resolve(true);
|
|
1151
1061
|
}
|
|
@@ -1162,52 +1072,30 @@ async function readSignatureFile(cwd) {
|
|
|
1162
1072
|
})(SignatureFileReader.decode(data));
|
|
1163
1073
|
});
|
|
1164
1074
|
}
|
|
1165
|
-
async function lsdir(dir) {
|
|
1166
|
-
return fs__default["default"].promises.readdir(dir).then((dirs) => {
|
|
1167
|
-
return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isDirectory()).map((subdirectory) => path__default["default"].join(dir, subdirectory));
|
|
1168
|
-
});
|
|
1169
|
-
}
|
|
1170
|
-
async function lsfiles(dir) {
|
|
1171
|
-
return fs__default["default"].promises.readdir(dir).then((dirs) => {
|
|
1172
|
-
return dirs.filter((name) => fs__default["default"].statSync(path__default["default"].join(dir, name)).isFile()).map((file) => path__default["default"].join(dir, file));
|
|
1173
|
-
});
|
|
1174
|
-
}
|
|
1175
1075
|
async function readDocuments(cwd) {
|
|
1176
1076
|
const documentDir = path__default["default"].join(cwd, "documents");
|
|
1177
1077
|
const dirs = await lsdir(documentDir);
|
|
1178
1078
|
const files = (await Promise.all(dirs.map((dir) => lsfiles(dir)))).flat();
|
|
1179
1079
|
const documentObj = files.reduce((acc, file) => {
|
|
1180
|
-
const fileContent = fs__default["default"].readFileSync(file, "utf-8");
|
|
1181
1080
|
const filename = path__default["default"].parse(file).name;
|
|
1182
|
-
|
|
1183
|
-
|
|
1081
|
+
const fileContent = fs__default["default"].readFileSync(file, "utf-8");
|
|
1082
|
+
const json = JSON.parse(fileContent);
|
|
1083
|
+
return { ...acc, [filename]: json };
|
|
1184
1084
|
}, {});
|
|
1185
|
-
return
|
|
1085
|
+
return documentObj;
|
|
1186
1086
|
}
|
|
1187
|
-
|
|
1087
|
+
async function sendDocuments(client, cwd) {
|
|
1188
1088
|
const pathToDocuments = path__default["default"].join(cwd, "documents");
|
|
1189
1089
|
const pathToSignatureFile = path__default["default"].join(pathToDocuments, "index.json");
|
|
1190
|
-
if (!fs__default["default"].existsSync(pathToSignatureFile))
|
|
1090
|
+
if (!fs__default["default"].existsSync(pathToSignatureFile))
|
|
1191
1091
|
return Promise.resolve(false);
|
|
1192
|
-
}
|
|
1193
1092
|
const signatureObj = await readSignatureFile(cwd);
|
|
1194
|
-
const
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
documents: documentsStr
|
|
1198
|
-
};
|
|
1199
|
-
const prismicUrl = new URL(base);
|
|
1200
|
-
prismicUrl.hostname = `${repository}.${prismicUrl.hostname}`;
|
|
1201
|
-
prismicUrl.pathname = "starter/documents";
|
|
1202
|
-
const endpointURL = prismicUrl.toString();
|
|
1093
|
+
const documents = await readDocuments(cwd);
|
|
1094
|
+
if (Object.keys(documents).length === 0)
|
|
1095
|
+
return Promise.resolve(false);
|
|
1203
1096
|
const spinner = spinner$1("Pushing existing documents to your repository");
|
|
1204
1097
|
spinner.start();
|
|
1205
|
-
return
|
|
1206
|
-
headers: {
|
|
1207
|
-
"User-Agent": "prismic-cli/0",
|
|
1208
|
-
Cookie: cookies
|
|
1209
|
-
}
|
|
1210
|
-
}).then(() => {
|
|
1098
|
+
return client.pushDocuments(signatureObj.signature, documents, SharedConfig.PrismicSharedConfigManager.get().cookies).then(() => {
|
|
1211
1099
|
spinner.succeed();
|
|
1212
1100
|
fs__default["default"].rmSync(pathToDocuments, { recursive: true, force: true });
|
|
1213
1101
|
return true;
|
|
@@ -1217,58 +1105,54 @@ const sendDocumentsFromStarter = async (repository, cookies, base, cwd) => {
|
|
|
1217
1105
|
if (((_a = e.response) == null ? void 0 : _a.data) === "Repository should not contain documents") {
|
|
1218
1106
|
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.");
|
|
1219
1107
|
} else {
|
|
1220
|
-
|
|
1108
|
+
writeError$1("Sending documents failed, please try again. If the problem persists, contact us.");
|
|
1109
|
+
writeError$1(`Full error: ${e.code || 500} - ${e.message}`);
|
|
1221
1110
|
}
|
|
1222
1111
|
process.exit(1);
|
|
1223
1112
|
});
|
|
1224
|
-
}
|
|
1113
|
+
}
|
|
1225
1114
|
|
|
1226
|
-
async function sendStarterData(
|
|
1227
|
-
const
|
|
1228
|
-
const
|
|
1229
|
-
const hasDocuments = NodeUtils.Files.exists(
|
|
1230
|
-
if (
|
|
1115
|
+
async function sendStarterData(client, cwd, pushDocuments = true) {
|
|
1116
|
+
const manifest = NodeUtils.retrieveManifest(cwd);
|
|
1117
|
+
const documentsPath = path__default["default"].join(cwd, "documents");
|
|
1118
|
+
const hasDocuments = NodeUtils.Files.exists(documentsPath);
|
|
1119
|
+
if (manifest.exists === false || hasDocuments === false)
|
|
1231
1120
|
return Promise.resolve(false);
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
if (sendDocs === false) {
|
|
1238
|
-
fs__default["default"].rmSync(pathToDocuments, { recursive: true, force: true });
|
|
1121
|
+
if (manifest.content)
|
|
1122
|
+
await sendSlices(client, cwd, manifest.content);
|
|
1123
|
+
await sendCustomTypes(client, cwd);
|
|
1124
|
+
if (!pushDocuments) {
|
|
1125
|
+
fs__default["default"].rmSync(documentsPath, { recursive: true, force: true });
|
|
1239
1126
|
return Promise.resolve(true);
|
|
1240
1127
|
}
|
|
1241
|
-
return
|
|
1128
|
+
return sendDocuments(client, cwd);
|
|
1242
1129
|
}
|
|
1243
1130
|
|
|
1244
1131
|
async function init() {
|
|
1245
1132
|
const cwd = findArgument(process.argv, "cwd") || process.cwd();
|
|
1246
|
-
const
|
|
1133
|
+
const mode = getApplicationMode(findArgument(process.argv, "mode")) || client.ApplicationMode.PROD;
|
|
1247
1134
|
const lib = findArgument(process.argv, "library");
|
|
1248
1135
|
const branch = findArgument(process.argv, "branch");
|
|
1249
1136
|
const isTrackingAvailable = findArgument(process.argv, "tracking") !== "false";
|
|
1250
|
-
const
|
|
1251
|
-
const
|
|
1137
|
+
const preSelectedRepository = findArgument(process.argv, "repository");
|
|
1138
|
+
const pushDocuments = !findFlag(process.argv, "no-docs");
|
|
1252
1139
|
Tracker.get().initialize("JfTfmHaATChc4xueS7RcCBsixI71dJIJ" , isTrackingAvailable);
|
|
1253
|
-
void Tracker.get().trackInitStart(
|
|
1140
|
+
void Tracker.get().trackInitStart(preSelectedRepository);
|
|
1141
|
+
const client$1 = new InitClient(mode, null, Prismic__default["default"].PrismicSharedConfigManager.getAuth());
|
|
1254
1142
|
console.log(purple("You're about to configure Slicemachine... Press ctrl + C to cancel"));
|
|
1255
1143
|
validatePkg(cwd);
|
|
1256
|
-
const user = await loginOrBypass(
|
|
1257
|
-
|
|
1258
|
-
throw new Error("The user should be logged in!");
|
|
1259
|
-
if (user.profile) {
|
|
1260
|
-
Tracker.get().identifyUser(user.profile.shortId, user.profile.intercomHash);
|
|
1261
|
-
}
|
|
1144
|
+
const user = await loginOrBypass(client$1);
|
|
1145
|
+
Tracker.get().identifyUser(user.shortId, user.intercomHash);
|
|
1262
1146
|
void Tracker.get().trackInitIdentify();
|
|
1263
|
-
const config = Prismic__default["default"].PrismicSharedConfigManager.get();
|
|
1264
1147
|
const frameworkResult = await detectFramework(cwd);
|
|
1265
|
-
const
|
|
1266
|
-
Tracker.get().setRepository(
|
|
1148
|
+
const repository = await chooseOrCreateARepository(client$1, cwd, frameworkResult.value, preSelectedRepository);
|
|
1149
|
+
Tracker.get().setRepository(repository);
|
|
1150
|
+
client$1.updateRepository(repository);
|
|
1267
1151
|
const sliceLibPath = lib ? await installLib(cwd, lib, branch) : void 0;
|
|
1268
|
-
const wasStarter = await sendStarterData(
|
|
1269
|
-
await configureProject(
|
|
1152
|
+
const wasStarter = await sendStarterData(client$1, cwd, pushDocuments);
|
|
1153
|
+
await configureProject(client$1, cwd, repository, frameworkResult, sliceLibPath, isTrackingAvailable);
|
|
1270
1154
|
await installRequiredDependencies(cwd, frameworkResult.value, wasStarter);
|
|
1271
|
-
displayFinalMessage(cwd, wasStarter,
|
|
1155
|
+
displayFinalMessage(cwd, wasStarter, repository, client$1.apisEndpoints.Wroom);
|
|
1272
1156
|
}
|
|
1273
1157
|
init().then(() => {
|
|
1274
1158
|
process.exit(0);
|