@slicemachine/init 2.2.7-dev-next-release.2 → 2.2.7-dev-next-release.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.
Files changed (65) hide show
  1. package/dist/SliceMachineInitProcess.cjs +130 -73
  2. package/dist/SliceMachineInitProcess.cjs.map +1 -1
  3. package/dist/SliceMachineInitProcess.d.ts +13 -0
  4. package/dist/SliceMachineInitProcess.js +130 -73
  5. package/dist/SliceMachineInitProcess.js.map +1 -1
  6. package/dist/_node_modules/@babel/code-frame/lib/index.cjs +1 -1
  7. package/dist/_node_modules/@babel/code-frame/lib/index.js +1 -1
  8. package/dist/_node_modules/@babel/highlight/lib/index.cjs +1 -1
  9. package/dist/_node_modules/@babel/highlight/lib/index.js +1 -1
  10. package/dist/_node_modules/@nodelib/fs.scandir/out/providers/async.cjs +1 -1
  11. package/dist/_node_modules/@nodelib/fs.scandir/out/providers/async.js +1 -1
  12. package/dist/_node_modules/@nodelib/fs.scandir/out/providers/sync.cjs +1 -1
  13. package/dist/_node_modules/@nodelib/fs.scandir/out/providers/sync.js +1 -1
  14. package/dist/_node_modules/@nodelib/fs.scandir/out/settings.cjs +1 -1
  15. package/dist/_node_modules/@nodelib/fs.scandir/out/settings.js +1 -1
  16. package/dist/_node_modules/@nodelib/fs.stat/out/index.cjs +1 -1
  17. package/dist/_node_modules/@nodelib/fs.stat/out/index.js +1 -1
  18. package/dist/_node_modules/@nodelib/fs.walk/out/index.cjs +1 -1
  19. package/dist/_node_modules/@nodelib/fs.walk/out/index.js +1 -1
  20. package/dist/_node_modules/dir-glob/index.cjs +2 -2
  21. package/dist/_node_modules/dir-glob/index.js +2 -2
  22. package/dist/_node_modules/fast-glob/out/index.cjs +1 -1
  23. package/dist/_node_modules/fast-glob/out/index.js +1 -1
  24. package/dist/_node_modules/fast-glob/out/managers/tasks.cjs +1 -1
  25. package/dist/_node_modules/fast-glob/out/managers/tasks.js +1 -1
  26. package/dist/_node_modules/fast-glob/out/providers/filters/deep.cjs +1 -1
  27. package/dist/_node_modules/fast-glob/out/providers/filters/deep.js +1 -1
  28. package/dist/_node_modules/fast-glob/out/providers/filters/entry.cjs +1 -1
  29. package/dist/_node_modules/fast-glob/out/providers/filters/entry.js +1 -1
  30. package/dist/_node_modules/fast-glob/out/providers/filters/error.cjs +1 -1
  31. package/dist/_node_modules/fast-glob/out/providers/filters/error.js +1 -1
  32. package/dist/_node_modules/fast-glob/out/providers/matchers/matcher.cjs +1 -1
  33. package/dist/_node_modules/fast-glob/out/providers/matchers/matcher.js +1 -1
  34. package/dist/_node_modules/fast-glob/out/providers/transformers/entry.cjs +1 -1
  35. package/dist/_node_modules/fast-glob/out/providers/transformers/entry.js +1 -1
  36. package/dist/_node_modules/fast-glob/out/readers/async.cjs +1 -1
  37. package/dist/_node_modules/fast-glob/out/readers/async.js +1 -1
  38. package/dist/_node_modules/fast-glob/out/readers/reader.cjs +2 -2
  39. package/dist/_node_modules/fast-glob/out/readers/reader.js +2 -2
  40. package/dist/_node_modules/fast-glob/out/readers/stream.cjs +2 -2
  41. package/dist/_node_modules/fast-glob/out/readers/stream.js +2 -2
  42. package/dist/_node_modules/fast-glob/out/readers/sync.cjs +2 -2
  43. package/dist/_node_modules/fast-glob/out/readers/sync.js +2 -2
  44. package/dist/_node_modules/fast-glob/out/utils/index.cjs +1 -1
  45. package/dist/_node_modules/fast-glob/out/utils/index.js +1 -1
  46. package/dist/_node_modules/map-obj/index.cjs +1 -1
  47. package/dist/_node_modules/map-obj/index.js +1 -1
  48. package/dist/_node_modules/path-type/index.cjs +1 -1
  49. package/dist/_node_modules/path-type/index.js +1 -1
  50. package/dist/_virtual/index10.cjs +2 -2
  51. package/dist/_virtual/index10.js +2 -2
  52. package/dist/_virtual/index12.cjs +2 -2
  53. package/dist/_virtual/index12.js +2 -2
  54. package/dist/_virtual/index3.cjs +2 -2
  55. package/dist/_virtual/index3.js +2 -2
  56. package/dist/_virtual/index4.cjs +2 -2
  57. package/dist/_virtual/index4.js +2 -2
  58. package/dist/_virtual/index5.cjs +2 -2
  59. package/dist/_virtual/index5.js +2 -2
  60. package/dist/_virtual/index6.cjs +2 -2
  61. package/dist/_virtual/index6.js +2 -2
  62. package/dist/packages/init/package.json.cjs +4 -4
  63. package/dist/packages/init/package.json.js +4 -4
  64. package/package.json +4 -4
  65. package/src/SliceMachineInitProcess.ts +199 -120
@@ -122,11 +122,11 @@ export class SliceMachineInitProcess {
122
122
  );
123
123
 
124
124
  await this.beginCoreDependenciesInstallation();
125
- await this.loginAndFetchUserData();
126
125
 
127
126
  if (this.options.repository) {
128
127
  await this.useRepositoryFlag();
129
128
  } else {
129
+ await this.loginAndFetchUserData();
130
130
  await this.selectRepository();
131
131
  }
132
132
 
@@ -135,12 +135,20 @@ export class SliceMachineInitProcess {
135
135
  "Repository selection must be available through context to proceed",
136
136
  );
137
137
 
138
+ await this.finishCoreDependenciesInstallation();
139
+ await this.upsertSliceMachineConfigurationAndStartPluginRunner();
140
+
141
+ const isLoginRequired = await this.checkIsLoginRequired();
142
+ if (isLoginRequired) {
143
+ await this.loginAndFetchUserData();
144
+ if (this.context.repository.exists) {
145
+ this.validateWriteAccess();
146
+ }
147
+ }
138
148
  if (!this.context.repository.exists) {
139
149
  await this.createNewRepository();
140
150
  }
141
151
 
142
- await this.finishCoreDependenciesInstallation();
143
- await this.upsertSliceMachineConfigurationAndStartPluginRunner();
144
152
  await this.pushDataToPrismic();
145
153
  await this.initializeProject();
146
154
  await this.initializePlugins();
@@ -215,6 +223,31 @@ export class SliceMachineInitProcess {
215
223
  }
216
224
  }
217
225
 
226
+ protected async checkIsLoginRequired(): Promise<boolean> {
227
+ try {
228
+ assertExists(this.context.repository, "");
229
+ if (this.context.repository.exists === false) {
230
+ return true;
231
+ }
232
+ const [slices, ctLibrary, documentsGlob] = await Promise.all([
233
+ this.readAllSlices(),
234
+ this.manager.customTypes.readCustomTypeLibrary(),
235
+ this.readDocuments(),
236
+ ]);
237
+ if (
238
+ slices.length > 0 ||
239
+ ctLibrary.ids.length > 0 ||
240
+ (documentsGlob !== undefined && documentsGlob.documents.length > 0)
241
+ ) {
242
+ return true;
243
+ }
244
+ } catch (e) {
245
+ return true;
246
+ }
247
+
248
+ return false;
249
+ }
250
+
218
251
  protected trackError = (error: unknown): Promise<void> => {
219
252
  // Transform error to string and prevent hitting Segment 500kb API limit or sending ridiculously long trace
220
253
  const safeError = (
@@ -350,6 +383,55 @@ export class SliceMachineInitProcess {
350
383
  ]);
351
384
  }
352
385
 
386
+ protected async fetchUserProfile(): Promise<void> {
387
+ this.context.userProfile = await this.manager.user.getProfile();
388
+
389
+ await this.manager.telemetry.identify({
390
+ userID: this.context.userProfile.shortId,
391
+ intercomHash: this.context.userProfile.intercomHash,
392
+ });
393
+ await this.manager.telemetry.track({
394
+ event: "command:init:identify",
395
+ repository: this.options.repository,
396
+ });
397
+ }
398
+
399
+ protected async fetchUserRepositories(): Promise<void> {
400
+ this.context.userRepositories =
401
+ await this.manager.prismicRepository.readAll();
402
+ }
403
+
404
+ protected validateWriteAccess(): void {
405
+ assertExists(
406
+ this.context.repository,
407
+ "Repository selection must be available through context to proceed",
408
+ );
409
+ assertExists(
410
+ this.context.userRepositories,
411
+ "User repositories must be available through context to validate write access",
412
+ );
413
+ const { domain } = this.context.repository;
414
+ const maybeRepository = this.context.userRepositories.find(
415
+ (repository) => repository.domain === domain,
416
+ );
417
+
418
+ if (maybeRepository) {
419
+ if (!this.manager.prismicRepository.hasWriteAccess(maybeRepository)) {
420
+ throw new Error(
421
+ `Cannot run init command with repository ${chalk.cyan(
422
+ maybeRepository.domain,
423
+ )}: you are not a developer or admin of this repository`,
424
+ );
425
+ }
426
+ } else {
427
+ throw new Error(
428
+ `Cannot validate write access for repository ${chalk.cyan(
429
+ domain,
430
+ )}: you are not part of this repository`,
431
+ );
432
+ }
433
+ }
434
+
353
435
  protected loginAndFetchUserData(): Promise<void> {
354
436
  return listrRun([
355
437
  {
@@ -388,18 +470,7 @@ export class SliceMachineInitProcess {
388
470
  {
389
471
  title: "Fetching user profile...",
390
472
  task: async (_, task) => {
391
- this.context.userProfile =
392
- await this.manager.user.getProfile();
393
-
394
- await this.manager.telemetry.identify({
395
- userID: this.context.userProfile.shortId,
396
- intercomHash: this.context.userProfile.intercomHash,
397
- });
398
- await this.manager.telemetry.track({
399
- event: "command:init:identify",
400
- repository: this.options.repository,
401
- });
402
-
473
+ await this.fetchUserProfile();
403
474
  parentTask.title = `Logged in as ${chalk.cyan(
404
475
  this.context.userProfile?.email,
405
476
  )}`;
@@ -409,9 +480,7 @@ export class SliceMachineInitProcess {
409
480
  {
410
481
  title: "Fetching user repositories...",
411
482
  task: async (_, task) => {
412
- this.context.userRepositories =
413
- await this.manager.prismicRepository.readAll();
414
-
483
+ await this.fetchUserRepositories();
415
484
  task.title = "Fetched user repositories";
416
485
  },
417
486
  },
@@ -428,39 +497,25 @@ export class SliceMachineInitProcess {
428
497
  {
429
498
  title: `Flag ${chalk.cyan("repository")} used, validating input...`,
430
499
  task: async (_, task) => {
431
- assertExists(
432
- this.context.userRepositories,
433
- "User repositories must be available through context to run `useRepositoryFlag`",
434
- );
435
500
  assertExists(
436
501
  this.options.repository,
437
502
  "Flag `repository` must be set to run `useRepositoryFlag`",
438
503
  );
439
-
440
504
  const domain = formatRepositoryDomain(this.options.repository);
505
+ const validation = await validateRepositoryDomainAndAvailability({
506
+ domain,
507
+ existsFn: (domain) =>
508
+ this.manager.prismicRepository.checkExists({ domain }),
509
+ });
441
510
 
442
- const maybeRepository = this.context.userRepositories.find(
443
- (repository) => repository.domain === domain,
444
- );
445
-
446
- if (maybeRepository) {
447
- if (
448
- !this.manager.prismicRepository.hasWriteAccess(maybeRepository)
449
- ) {
450
- throw new Error(
451
- `Cannot run init command with repository ${chalk.cyan(
452
- maybeRepository.domain,
453
- )}: you are not a developer or admin of this repository`,
454
- );
455
- }
456
- } else {
457
- const validation = await validateRepositoryDomainAndAvailability({
458
- domain,
459
- existsFn: (domain) =>
460
- this.manager.prismicRepository.checkExists({ domain }),
461
- });
511
+ if (validation.LessThan4 || validation.MoreThan30) {
462
512
  const errorMessage = getErrorMessageForRepositoryDomainValidation({
463
- validation,
513
+ validation: {
514
+ ...validation,
515
+ // We don't want to throw if repo already exists.
516
+ // User most probably just created it via their dashboard.
517
+ AlreadyExists: false,
518
+ },
464
519
  displayDomain: chalk.cyan(domain),
465
520
  });
466
521
 
@@ -475,7 +530,7 @@ export class SliceMachineInitProcess {
475
530
 
476
531
  this.context.repository = {
477
532
  domain,
478
- exists: !!maybeRepository,
533
+ exists: validation.AlreadyExists ?? false,
479
534
  };
480
535
  },
481
536
  },
@@ -835,6 +890,58 @@ ${chalk.cyan("?")} Your Prismic repository name`.replace("\n", ""),
835
890
  ]);
836
891
  }
837
892
 
893
+ protected async readAllSlices(): Promise<
894
+ { libraryID: string; sliceID: string }[]
895
+ > {
896
+ const { libraries, errors } =
897
+ await this.manager.slices.readAllSliceLibraries();
898
+
899
+ if (errors.length > 0) {
900
+ // TODO: Provide better error message.
901
+ throw new Error(`Failed to read slice libraries: ${errors.join(", ")}`);
902
+ }
903
+
904
+ const slices: { libraryID: string; sliceID: string }[] = [];
905
+ for (const library of libraries) {
906
+ if (library.sliceIDs) {
907
+ for (const sliceID of library.sliceIDs) {
908
+ slices.push({
909
+ libraryID: library.libraryID,
910
+ sliceID,
911
+ });
912
+ }
913
+ }
914
+ }
915
+
916
+ return slices;
917
+ }
918
+
919
+ protected async readDocuments(): Promise<
920
+ | {
921
+ signature: string;
922
+ documents: string[];
923
+ directoryPath: string;
924
+ }
925
+ | undefined
926
+ > {
927
+ const root = await this.manager.project.getRoot();
928
+ const documentsDirectoryPath = path.resolve(root, "documents");
929
+ try {
930
+ await fs.access(documentsDirectoryPath);
931
+ } catch {
932
+ return;
933
+ }
934
+ const signaturePath = path.resolve(documentsDirectoryPath, "index.json");
935
+ const rawSignature = await fs.readFile(signaturePath, "utf-8");
936
+ const signature: string = JSON.parse(rawSignature).signature;
937
+
938
+ const documents = await globby("*/*.json", {
939
+ cwd: documentsDirectoryPath,
940
+ });
941
+
942
+ return { signature, documents, directoryPath: documentsDirectoryPath };
943
+ }
944
+
838
945
  protected pushDataToPrismic(): Promise<void> {
839
946
  return listrRun([
840
947
  {
@@ -851,27 +958,7 @@ ${chalk.cyan("?")} Your Prismic repository name`.replace("\n", ""),
851
958
  }
852
959
  },
853
960
  task: async (_, task) => {
854
- const { libraries, errors } =
855
- await this.manager.slices.readAllSliceLibraries();
856
-
857
- if (errors.length > 0) {
858
- // TODO: Provide better error message.
859
- throw new Error(
860
- `Failed to read slice libraries: ${errors.join(", ")}`,
861
- );
862
- }
863
-
864
- const slices: { libraryID: string; sliceID: string }[] = [];
865
- for (const library of libraries) {
866
- if (library.sliceIDs) {
867
- for (const sliceID of library.sliceIDs) {
868
- slices.push({
869
- libraryID: library.libraryID,
870
- sliceID,
871
- });
872
- }
873
- }
874
- }
961
+ const slices = await this.readAllSlices();
875
962
 
876
963
  if (slices.length === 0) {
877
964
  task.skip("No slice to push");
@@ -951,70 +1038,62 @@ ${chalk.cyan("?")} Your Prismic repository name`.replace("\n", ""),
951
1038
  "Repository selection must be available through context to run `pushDataToPrismic`",
952
1039
  );
953
1040
 
954
- const root = await this.manager.project.getRoot();
955
- const documentsDirectoryPath = path.resolve(root, "documents");
956
-
957
1041
  try {
958
- await fs.access(documentsDirectoryPath);
959
- } catch {
960
- parentTask.title = "Pushed data to Prismic";
961
- task.skip("No document to push");
1042
+ const documentsRead = await this.readDocuments();
962
1043
 
963
- return;
964
- }
965
-
966
- const signaturePath = path.resolve(
967
- documentsDirectoryPath,
968
- "index.json",
969
- );
970
- const rawSignature = await fs.readFile(signaturePath, "utf-8");
971
- const signature: string = JSON.parse(rawSignature).signature;
1044
+ if (
1045
+ documentsRead === undefined ||
1046
+ documentsRead.documents.length === 0
1047
+ ) {
1048
+ parentTask.title = "Pushed data to Prismic";
1049
+ task.skip("No document to push");
972
1050
 
973
- const documentsGlob = await globby("*/*.json", {
974
- cwd: documentsDirectoryPath,
975
- });
976
- if (documentsGlob.length === 0) {
977
- parentTask.title = "Pushed data to Prismic";
978
- task.skip("No document to push");
1051
+ return;
1052
+ }
979
1053
 
980
- return;
981
- }
1054
+ const { signature, documents, directoryPath } = documentsRead;
982
1055
 
983
- // TODO: Replace `unknown` with a Prismic document type.
984
- // The exact format is not know at this time, hence the `unknown`.
985
- const documents: Record<string, unknown> = {};
1056
+ // TODO: Replace `unknown` with a Prismic document type.
1057
+ // The exact format is not know at this time, hence the `unknown`.
1058
+ const recordDocument: Record<string, unknown> = {};
986
1059
 
987
- await Promise.all(
988
- documentsGlob.map(async (documentPath) => {
989
- const filename = path.basename(documentPath, ".json");
990
- const fileContent = await fs.readFile(
991
- path.resolve(documentsDirectoryPath, documentPath),
992
- "utf-8",
993
- );
1060
+ await Promise.all(
1061
+ documents.map(async (documentPath) => {
1062
+ const filename = path.basename(documentPath, ".json");
1063
+ const fileContent = await fs.readFile(
1064
+ path.resolve(directoryPath, documentPath),
1065
+ "utf-8",
1066
+ );
994
1067
 
995
- try {
996
- // TOOD: Validate the contents of the JSON file and skip on invalid documents.
997
- const parsedContents = JSON.parse(fileContent);
1068
+ try {
1069
+ // TOOD: Validate the contents of the JSON file and skip on invalid documents.
1070
+ const parsedContents = JSON.parse(fileContent);
1071
+
1072
+ recordDocument[filename] = parsedContents;
1073
+ } catch {
1074
+ // We prefer to manually allow console logs despite the app being a CLI to catch wild/unwanted console logs better
1075
+ // eslint-disable-next-line no-console
1076
+ console.log(
1077
+ `Skipped document due to its invalid format: ${documentPath}`,
1078
+ );
1079
+ }
1080
+ }),
1081
+ );
998
1082
 
999
- documents[filename] = parsedContents;
1000
- } catch {
1001
- // We prefer to manually allow console logs despite the app being a CLI to catch wild/unwanted console logs better
1002
- // eslint-disable-next-line no-console
1003
- console.log(
1004
- `Skipped document due to its invalid format: ${documentPath}`,
1005
- );
1006
- }
1007
- }),
1008
- );
1083
+ await this.manager.prismicRepository.pushDocuments({
1084
+ domain: this.context.repository.domain,
1085
+ documents: recordDocument,
1086
+ signature,
1087
+ });
1009
1088
 
1010
- await this.manager.prismicRepository.pushDocuments({
1011
- domain: this.context.repository.domain,
1012
- documents,
1013
- signature,
1014
- });
1089
+ task.title = "Pushed all documents";
1090
+ parentTask.title = "Pushed data to Prismic";
1091
+ } catch {
1092
+ parentTask.title = "Pushed data to Prismic";
1093
+ task.skip("No document to push");
1015
1094
 
1016
- task.title = "Pushed all documents";
1017
- parentTask.title = "Pushed data to Prismic";
1095
+ return;
1096
+ }
1018
1097
  },
1019
1098
  },
1020
1099
  {