directus-template-cli 0.7.0-beta.4 → 0.7.0-beta.6

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 (105) hide show
  1. package/bin/dev.js +6 -0
  2. package/bin/run.js +5 -0
  3. package/dist/commands/apply.d.ts +17 -17
  4. package/dist/commands/apply.js +163 -173
  5. package/dist/commands/base.d.ts +15 -0
  6. package/dist/commands/base.js +45 -0
  7. package/dist/commands/extract.d.ts +16 -7
  8. package/dist/commands/extract.js +80 -73
  9. package/dist/commands/init.d.ts +20 -15
  10. package/dist/commands/init.js +189 -126
  11. package/dist/flags/common.d.ts +8 -7
  12. package/dist/flags/common.js +13 -11
  13. package/dist/index.js +1 -5
  14. package/dist/lib/constants.d.ts +3 -5
  15. package/dist/lib/constants.js +8 -13
  16. package/dist/lib/extract/extract-access.js +11 -15
  17. package/dist/lib/extract/extract-assets.js +20 -25
  18. package/dist/lib/extract/extract-collections.js +12 -16
  19. package/dist/lib/extract/extract-content.js +14 -19
  20. package/dist/lib/extract/extract-dashboards.js +22 -28
  21. package/dist/lib/extract/extract-extensions.js +12 -16
  22. package/dist/lib/extract/extract-fields.js +13 -17
  23. package/dist/lib/extract/extract-files.js +15 -19
  24. package/dist/lib/extract/extract-flows.js +22 -28
  25. package/dist/lib/extract/extract-folders.js +15 -19
  26. package/dist/lib/extract/extract-permissions.js +12 -16
  27. package/dist/lib/extract/extract-policies.js +12 -16
  28. package/dist/lib/extract/extract-presets.js +12 -16
  29. package/dist/lib/extract/extract-relations.js +14 -18
  30. package/dist/lib/extract/extract-roles.js +15 -19
  31. package/dist/lib/extract/extract-schema.js +17 -21
  32. package/dist/lib/extract/extract-settings.js +12 -16
  33. package/dist/lib/extract/extract-translations.js +12 -16
  34. package/dist/lib/extract/extract-users.js +15 -19
  35. package/dist/lib/extract/index.js +47 -51
  36. package/dist/lib/init/config.d.ts +1 -1
  37. package/dist/lib/init/config.js +3 -6
  38. package/dist/lib/init/index.d.ts +5 -9
  39. package/dist/lib/init/index.js +105 -85
  40. package/dist/lib/init/types.js +1 -2
  41. package/dist/lib/load/apply-flags.js +17 -23
  42. package/dist/lib/load/index.d.ts +1 -12
  43. package/dist/lib/load/index.js +40 -44
  44. package/dist/lib/load/load-access.js +15 -20
  45. package/dist/lib/load/load-collections.js +27 -32
  46. package/dist/lib/load/load-dashboards.js +19 -25
  47. package/dist/lib/load/load-data.js +43 -49
  48. package/dist/lib/load/load-extensions.js +30 -38
  49. package/dist/lib/load/load-files.js +20 -24
  50. package/dist/lib/load/load-flows.js +23 -29
  51. package/dist/lib/load/load-folders.js +16 -20
  52. package/dist/lib/load/load-permissions.js +13 -17
  53. package/dist/lib/load/load-policies.js +14 -18
  54. package/dist/lib/load/load-presets.js +14 -18
  55. package/dist/lib/load/load-relations.d.ts +2 -0
  56. package/dist/lib/load/load-relations.js +16 -18
  57. package/dist/lib/load/load-roles.js +19 -23
  58. package/dist/lib/load/load-settings.js +18 -21
  59. package/dist/lib/load/load-translations.js +14 -18
  60. package/dist/lib/load/load-users.js +21 -25
  61. package/dist/lib/load/update-required-fields.js +13 -17
  62. package/dist/lib/sdk.d.ts +1 -2
  63. package/dist/lib/sdk.js +27 -27
  64. package/dist/lib/types/extension.js +1 -2
  65. package/dist/lib/types.d.ts +18 -0
  66. package/dist/lib/types.js +1 -0
  67. package/dist/lib/utils/animated-bunny.js +9 -14
  68. package/dist/lib/utils/auth.d.ts +8 -6
  69. package/dist/lib/utils/auth.js +48 -39
  70. package/dist/lib/utils/catch-error.js +8 -11
  71. package/dist/lib/utils/check-template.js +4 -8
  72. package/dist/lib/utils/chunk-array.js +1 -5
  73. package/dist/lib/utils/ensure-dir.js +7 -12
  74. package/dist/lib/utils/filter-fields.js +1 -4
  75. package/dist/lib/utils/get-role-ids.d.ts +1 -1
  76. package/dist/lib/utils/get-role-ids.js +7 -12
  77. package/dist/lib/utils/get-template.js +33 -37
  78. package/dist/lib/utils/logger.js +11 -13
  79. package/dist/lib/utils/open-url.js +5 -8
  80. package/dist/lib/utils/parse-github-url.d.ts +10 -5
  81. package/dist/lib/utils/parse-github-url.js +80 -45
  82. package/dist/lib/utils/path.js +6 -10
  83. package/dist/lib/utils/protected-domains.js +1 -4
  84. package/dist/lib/utils/read-file.js +8 -12
  85. package/dist/lib/utils/read-templates.js +9 -15
  86. package/dist/lib/utils/sanitize-flags.d.ts +3 -0
  87. package/dist/lib/utils/sanitize-flags.js +4 -0
  88. package/dist/lib/utils/system-fields.js +19 -22
  89. package/dist/lib/utils/template-config.d.ts +16 -0
  90. package/dist/lib/utils/template-config.js +34 -0
  91. package/dist/lib/utils/template-defaults.d.ts +1 -1
  92. package/dist/lib/utils/template-defaults.js +5 -14
  93. package/dist/lib/utils/transform-github-url.js +1 -5
  94. package/dist/lib/utils/validate-url.js +3 -6
  95. package/dist/lib/utils/wait.js +1 -5
  96. package/dist/lib/utils/write-to-file.js +8 -11
  97. package/dist/services/docker.js +68 -21
  98. package/dist/services/github.d.ts +1 -1
  99. package/dist/services/github.js +53 -22
  100. package/dist/services/posthog.d.ts +37 -0
  101. package/dist/services/posthog.js +104 -0
  102. package/oclif.manifest.json +32 -13
  103. package/package.json +38 -33
  104. package/bin/dev +0 -17
  105. package/bin/run +0 -5
@@ -1,19 +1,16 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const sdk_1 = require("@directus/sdk");
5
- const core_1 = require("@oclif/core");
6
- const constants_1 = require("../constants");
7
- const sdk_2 = require("../sdk");
8
- const catch_error_1 = tslib_1.__importDefault(require("../utils/catch-error"));
9
- const get_role_ids_1 = tslib_1.__importDefault(require("../utils/get-role-ids"));
10
- const read_file_1 = tslib_1.__importDefault(require("../utils/read-file"));
11
- async function loadUsers(dir) {
12
- const users = (0, read_file_1.default)('users', dir);
13
- core_1.ux.action.start(core_1.ux.colorize(constants_1.DIRECTUS_PINK, `Loading ${users.length} users`));
1
+ import { createUser, readUsers } from '@directus/sdk';
2
+ import { ux } from '@oclif/core';
3
+ import { DIRECTUS_PINK } from '../constants.js';
4
+ import { api } from '../sdk.js';
5
+ import catchError from '../utils/catch-error.js';
6
+ import getRoleIds from '../utils/get-role-ids.js';
7
+ import readFile from '../utils/read-file.js';
8
+ export default async function loadUsers(dir) {
9
+ const users = readFile('users', dir);
10
+ ux.action.start(ux.colorize(DIRECTUS_PINK, `Loading ${users.length} users`));
14
11
  if (users && users.length > 0) {
15
- const { legacyAdminRoleId, newAdminRoleId } = await (0, get_role_ids_1.default)(dir);
16
- const existingUsers = await sdk_2.api.client.request((0, sdk_1.readUsers)({
12
+ const { legacyAdminRoleId, newAdminRoleId } = await getRoleIds(dir);
13
+ const existingUsers = await api.client.request(readUsers({
17
14
  limit: -1,
18
15
  }));
19
16
  const filteredUsers = users.map(user => {
@@ -21,11 +18,11 @@ async function loadUsers(dir) {
21
18
  const isAdmin = user.role === legacyAdminRoleId;
22
19
  user.role = isAdmin ? newAdminRoleId : user.role;
23
20
  // Delete the unneeded fields
24
- delete user.last_page;
25
- delete user.token;
26
- delete user.policies;
21
+ user.last_page = undefined;
22
+ user.token = undefined;
23
+ user.policies = undefined;
27
24
  // Delete passwords to prevent setting to *******
28
- delete user.password;
25
+ user.password = undefined;
29
26
  return user;
30
27
  });
31
28
  for await (const user of filteredUsers) {
@@ -41,20 +38,19 @@ async function loadUsers(dir) {
41
38
  }
42
39
  if (existingUserWithSameEmail) {
43
40
  // Delete email if there's an existing user with the same email but different id
44
- delete user.email;
41
+ user.email = undefined;
45
42
  }
46
43
  if (user.email === null) {
47
44
  // Delete email if it's null
48
- delete user.email;
45
+ user.email = undefined;
49
46
  }
50
47
  try {
51
- await sdk_2.api.client.request((0, sdk_1.createUser)(user));
48
+ await api.client.request(createUser(user));
52
49
  }
53
50
  catch (error) {
54
- (0, catch_error_1.default)(error);
51
+ catchError(error);
55
52
  }
56
53
  }
57
54
  }
58
- core_1.ux.action.stop();
55
+ ux.action.stop();
59
56
  }
60
- exports.default = loadUsers;
@@ -1,24 +1,20 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const sdk_1 = require("@directus/sdk");
5
- const core_1 = require("@oclif/core");
6
- const constants_1 = require("../constants");
7
- const sdk_2 = require("../sdk");
8
- const catch_error_1 = tslib_1.__importDefault(require("../utils/catch-error"));
9
- const read_file_1 = tslib_1.__importDefault(require("../utils/read-file"));
10
- async function updateRequiredFields(dir) {
11
- const fieldsToUpdate = (0, read_file_1.default)('fields', dir)
12
- .filter(field => { var _a, _b; return field.meta.required === true || ((_a = field.schema) === null || _a === void 0 ? void 0 : _a.is_nullable) === false || ((_b = field.schema) === null || _b === void 0 ? void 0 : _b.is_unique) === true; });
13
- core_1.ux.action.start(core_1.ux.colorize(constants_1.DIRECTUS_PINK, `Updating ${fieldsToUpdate.length} fields to required`));
1
+ import { updateField } from '@directus/sdk';
2
+ import { ux } from '@oclif/core';
3
+ import { DIRECTUS_PINK } from '../constants.js';
4
+ import { api } from '../sdk.js';
5
+ import catchError from '../utils/catch-error.js';
6
+ import readFile from '../utils/read-file.js';
7
+ export default async function updateRequiredFields(dir) {
8
+ const fieldsToUpdate = readFile('fields', dir)
9
+ .filter(field => field.meta.required === true || field.schema?.is_nullable === false || field.schema?.is_unique === true);
10
+ ux.action.start(ux.colorize(DIRECTUS_PINK, `Updating ${fieldsToUpdate.length} fields to required`));
14
11
  for await (const field of fieldsToUpdate) {
15
12
  try {
16
- await sdk_2.api.client.request((0, sdk_1.updateField)(field.collection, field.field, { meta: { ...field.meta }, schema: { ...field.schema } }));
13
+ await api.client.request(updateField(field.collection, field.field, { meta: { ...field.meta }, schema: { ...field.schema } }));
17
14
  }
18
15
  catch (error) {
19
- (0, catch_error_1.default)(error);
16
+ catchError(error);
20
17
  }
21
18
  }
22
- core_1.ux.action.stop();
19
+ ux.action.stop();
23
20
  }
24
- exports.default = updateRequiredFields;
package/dist/lib/sdk.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import type { AuthenticationClient, RestClient } from '@directus/sdk';
2
- export interface Schema {
3
- }
2
+ type Schema = any;
4
3
  export declare class DirectusError extends Error {
5
4
  errors: Array<{
6
5
  extensions?: Record<string, unknown>;
package/dist/lib/sdk.js CHANGED
@@ -1,11 +1,12 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.api = exports.DirectusError = void 0;
4
- const tslib_1 = require("tslib");
5
- const sdk_1 = require("@directus/sdk");
6
- const core_1 = require("@oclif/core");
7
- const bottleneck_1 = tslib_1.__importDefault(require("bottleneck"));
8
- class DirectusError extends Error {
1
+ import { authentication, createDirectus, rest } from '@directus/sdk';
2
+ import { ux } from '@oclif/core';
3
+ import Bottleneck from 'bottleneck';
4
+ export class DirectusError extends Error {
5
+ errors;
6
+ headers;
7
+ message;
8
+ response;
9
+ status;
9
10
  constructor(response) {
10
11
  super(response.statusText);
11
12
  this.name = 'DirectusError';
@@ -39,11 +40,12 @@ class DirectusError extends Error {
39
40
  }
40
41
  }
41
42
  }
42
- exports.DirectusError = DirectusError;
43
43
  class Api {
44
+ client;
45
+ authData = null;
46
+ limiter;
44
47
  constructor() {
45
- this.authData = null;
46
- this.limiter = new bottleneck_1.default({
48
+ this.limiter = new Bottleneck({
47
49
  maxConcurrent: 10,
48
50
  minTime: 100, // Ensure at least 100ms between requests
49
51
  reservoir: 50, // Reservoir to handle the default rate limiter of 50 requests per second
@@ -52,18 +54,17 @@ class Api {
52
54
  retryCount: 3, // Retry a maximum of 3 times
53
55
  });
54
56
  this.limiter.on('failed', async (error, jobInfo) => {
55
- var _a;
56
57
  if (error instanceof DirectusError) {
57
- const retryAfter = (_a = error.headers) === null || _a === void 0 ? void 0 : _a.get('Retry-After');
58
+ const retryAfter = error.headers?.get('Retry-After');
58
59
  const statusCode = error.status;
59
60
  if (statusCode === 429) {
60
- const delay = retryAfter ? Number.parseInt(retryAfter, 10) * 1000 : 60000;
61
- core_1.ux.log(`${core_1.ux.colorize('dim', '--')} Rate limited. Retrying after ${delay}ms`);
61
+ const delay = retryAfter ? Number.parseInt(retryAfter, 10) * 1000 : 60_000;
62
+ ux.stdout(`${ux.colorize('dim', '--')} Rate limited. Retrying after ${delay}ms`);
62
63
  return delay;
63
64
  }
64
65
  if (statusCode === 503) {
65
66
  const delay = retryAfter ? Number.parseInt(retryAfter, 10) * 1000 : 5000;
66
- core_1.ux.log(`${core_1.ux.colorize('dim', '--')} Server under pressure. Retrying after ${delay}ms`);
67
+ ux.stdout(`${ux.colorize('dim', '--')} Server under pressure. Retrying after ${delay}ms`);
67
68
  return delay;
68
69
  }
69
70
  // If the status code is 400 or 401, we don't want to retry
@@ -73,33 +74,32 @@ class Api {
73
74
  }
74
75
  // For other errors, use exponential backoff, but only if we haven't exceeded retryCount
75
76
  if (jobInfo.retryCount < 3) {
76
- const delay = Math.min(1000 * 2 ** jobInfo.retryCount, 30000);
77
- core_1.ux.log(`${core_1.ux.colorize('dim', '--')} Request failed. Retrying after ${delay}ms`);
77
+ const delay = Math.min(1000 * 2 ** jobInfo.retryCount, 30_000);
78
+ ux.stdout(`${ux.colorize('dim', '--')} Request failed. Retrying after ${delay}ms`);
78
79
  return delay;
79
80
  }
80
- core_1.ux.log(`${core_1.ux.colorize('dim', '--')} Max retries reached, not retrying further`);
81
+ ux.stdout(`${ux.colorize('dim', '--')} Max retries reached, not retrying further`);
81
82
  });
82
83
  this.limiter.on('retry', (error, jobInfo) => {
83
- core_1.ux.log(`${core_1.ux.colorize('dim', '--')} Retrying job (attempt ${jobInfo.retryCount + 1})`);
84
+ ux.stdout(`${ux.colorize('dim', '--')} Retrying job (attempt ${jobInfo.retryCount + 1})`);
84
85
  });
85
86
  this.limiter.on('depleted', empty => {
86
87
  if (empty) {
87
- core_1.ux.log(`${core_1.ux.colorize('dim', '--')} Rate limit quota depleted. Requests will be queued.`);
88
+ ux.stdout(`${ux.colorize('dim', '--')} Rate limit quota depleted. Requests will be queued.`);
88
89
  }
89
90
  });
90
91
  }
91
92
  getToken() {
92
- var _a, _b;
93
- return (_b = (_a = this.authData) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : null;
93
+ return this.authData?.access_token ?? null;
94
94
  }
95
95
  initialize(url) {
96
- this.client = (0, sdk_1.createDirectus)(url, {
96
+ this.client = createDirectus(url, {
97
97
  globals: {
98
98
  fetch: this.limiter.wrap(this.enhancedFetch),
99
99
  },
100
100
  })
101
- .with((0, sdk_1.rest)())
102
- .with((0, sdk_1.authentication)('json', {
101
+ .with(rest())
102
+ .with(authentication('json', {
103
103
  autoRefresh: true,
104
104
  storage: {
105
105
  get: () => this.authData,
@@ -145,4 +145,4 @@ class Api {
145
145
  }
146
146
  }
147
147
  const api = new Api();
148
- exports.api = api;
148
+ export { api };
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
@@ -0,0 +1,18 @@
1
+ export interface DirectusTemplateFrontend {
2
+ name: string;
3
+ path: string;
4
+ }
5
+ export interface DirectusTemplateConfig {
6
+ name: string;
7
+ description: string;
8
+ template: string;
9
+ frontends: {
10
+ [key: string]: DirectusTemplateFrontend;
11
+ };
12
+ }
13
+ export interface TemplatePackageJson {
14
+ name: string;
15
+ version: string;
16
+ description: string;
17
+ 'directus:template'?: DirectusTemplateConfig;
18
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,19 +1,15 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.animatedBunny = exports.RANDOM_SAYINGS = void 0;
4
- const tslib_1 = require("tslib");
5
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
6
- const log_update_1 = tslib_1.__importDefault(require("log-update"));
7
- const constants_1 = require("../constants");
8
- exports.RANDOM_SAYINGS = [
1
+ import chalk from 'chalk';
2
+ import logUpdate from 'log-update';
3
+ import { DIRECTUS_PINK } from '../constants.js';
4
+ export const RANDOM_SAYINGS = [
9
5
  'One does not simply write backends...',
10
6
  'I don\'t always test my code, but when I do, I use production.',
11
7
  'A wild Directus appears!',
12
8
  'Error 418: I\'m a teapot. Just kidding, I\'m Directus and I\'ve got your backend covered.',
13
9
  'I\'ll fix it later. Narrator: They didn\'t fix it later.',
14
10
  ];
15
- async function animatedBunny(customMessage) {
16
- const saying = customMessage || exports.RANDOM_SAYINGS[Math.floor(Math.random() * exports.RANDOM_SAYINGS.length)];
11
+ export async function animatedBunny(customMessage) {
12
+ const saying = customMessage || RANDOM_SAYINGS[Math.floor(Math.random() * RANDOM_SAYINGS.length)];
17
13
  let typedSaying = '';
18
14
  let blinkState = true;
19
15
  let charIndex = 0;
@@ -24,7 +20,7 @@ async function animatedBunny(customMessage) {
24
20
  isCleanedUp = true;
25
21
  clearInterval(animation);
26
22
  clearInterval(typing);
27
- log_update_1.default.done();
23
+ logUpdate.done();
28
24
  };
29
25
  // Ensure cleanup on process exit
30
26
  process.on('exit', cleanup);
@@ -36,8 +32,8 @@ async function animatedBunny(customMessage) {
36
32
  if (isCleanedUp)
37
33
  return;
38
34
  const eyes = blinkState ? '- -' : 'Õ Õ';
39
- const frame = `(\\ /)\n \\\\_//\n ( ${eyes}) ${chalk_1.default.dim('')}${chalk_1.default.hex(constants_1.DIRECTUS_PINK).visible(`"${typedSaying}"`)}\nC(")(")`;
40
- (0, log_update_1.default)(frame);
35
+ const frame = `(\\ /)\n \\\\_//\n ( ${eyes}) ${chalk.dim('')}${chalk.hex(DIRECTUS_PINK).visible(`"${typedSaying}"`)}\nC(")(")`;
36
+ logUpdate(frame);
41
37
  };
42
38
  const animation = setInterval(() => {
43
39
  blinkState = !blinkState;
@@ -64,4 +60,3 @@ async function animatedBunny(customMessage) {
64
60
  process.removeListener('SIGINT', cleanup);
65
61
  }
66
62
  }
67
- exports.animatedBunny = animatedBunny;
@@ -16,13 +16,15 @@ export declare function getDirectusUrl(): Promise<string>;
16
16
  */
17
17
  export declare function getDirectusToken(directusUrl: string): Promise<string>;
18
18
  /**
19
- * Initialize the Directus API with the provided flags
20
- * @param flags - The validated ApplyFlags
21
- */
19
+ * Initialize the Directus API with the provided flags and log in the user
20
+ * @param flags - The validated ApplyFlags
21
+ * @returns {Promise<void>} - Returns nothing
22
+ */
22
23
  export declare function initializeDirectusApi(flags: AuthFlags): Promise<void>;
23
24
  /**
24
- * Validate the authentication flags
25
- * @param flags - The AuthFlags
26
- */
25
+ * Validate the authentication flags
26
+ * @param flags - The AuthFlags
27
+ * @returns {void} - Errors if the flags are invalid
28
+ */
27
29
  export declare function validateAuthFlags(flags: AuthFlags): void;
28
30
  export {};
@@ -1,42 +1,52 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateAuthFlags = exports.initializeDirectusApi = exports.getDirectusToken = exports.getDirectusUrl = void 0;
4
- const tslib_1 = require("tslib");
5
- const sdk_1 = require("@directus/sdk");
6
- const core_1 = require("@oclif/core");
7
- const sdk_2 = require("../sdk");
8
- const catch_error_1 = tslib_1.__importDefault(require("./catch-error"));
9
- const validate_url_1 = tslib_1.__importDefault(require("./validate-url"));
1
+ import { readMe } from '@directus/sdk';
2
+ import { text, log, isCancel } from '@clack/prompts';
3
+ import { ux } from '@oclif/core';
4
+ import { api } from '../sdk.js';
5
+ import catchError from './catch-error.js';
6
+ import validateUrl from './validate-url.js';
10
7
  /**
11
8
  * Get the Directus URL from the user
12
9
  * @returns The Directus URL
13
10
  */
14
- async function getDirectusUrl() {
15
- const directusUrl = await core_1.ux.prompt('What is your Directus URL?', { default: 'http://localhost:8055' });
11
+ export async function getDirectusUrl() {
12
+ const directusUrl = await text({
13
+ placeholder: 'http://localhost:8055',
14
+ message: 'What is your Directus URL?',
15
+ });
16
+ if (isCancel(directusUrl)) {
17
+ log.info('Exiting...');
18
+ ux.exit(0);
19
+ }
16
20
  // Validate URL
17
- if (!(0, validate_url_1.default)(directusUrl)) {
18
- core_1.ux.warn('Invalid URL');
21
+ if (!validateUrl(directusUrl)) {
22
+ ux.warn('Invalid URL');
19
23
  return getDirectusUrl();
20
24
  }
21
- sdk_2.api.initialize(directusUrl);
25
+ api.initialize(directusUrl);
22
26
  return directusUrl;
23
27
  }
24
- exports.getDirectusUrl = getDirectusUrl;
25
28
  /**
26
29
  * Get the Directus token from the user
27
30
  * @param directusUrl - The Directus URL
28
31
  * @returns The Directus token
29
32
  */
30
- async function getDirectusToken(directusUrl) {
31
- const directusToken = await core_1.ux.prompt('What is your Directus Admin Token?');
33
+ export async function getDirectusToken(directusUrl) {
34
+ const directusToken = await text({
35
+ placeholder: 'admin-token-here',
36
+ message: 'What is your Directus Admin Token?',
37
+ });
38
+ if (isCancel(directusToken)) {
39
+ log.info('Exiting...');
40
+ ux.exit(0);
41
+ }
32
42
  // Validate token by fetching the user
33
43
  try {
34
- await sdk_2.api.loginWithToken(directusToken);
35
- const response = await sdk_2.api.client.request((0, sdk_1.readMe)());
44
+ await api.loginWithToken(directusToken);
45
+ const response = await api.client.request(readMe());
36
46
  return directusToken;
37
47
  }
38
48
  catch (error) {
39
- (0, catch_error_1.default)(error, {
49
+ catchError(error, {
40
50
  context: {
41
51
  directusUrl,
42
52
  message: 'Invalid token. Please try again.',
@@ -46,40 +56,39 @@ async function getDirectusToken(directusUrl) {
46
56
  return getDirectusToken(directusUrl);
47
57
  }
48
58
  }
49
- exports.getDirectusToken = getDirectusToken;
50
59
  /**
51
- * Initialize the Directus API with the provided flags
52
- * @param flags - The validated ApplyFlags
53
- */
54
- async function initializeDirectusApi(flags) {
55
- sdk_2.api.initialize(flags.directusUrl);
60
+ * Initialize the Directus API with the provided flags and log in the user
61
+ * @param flags - The validated ApplyFlags
62
+ * @returns {Promise<void>} - Returns nothing
63
+ */
64
+ export async function initializeDirectusApi(flags) {
65
+ api.initialize(flags.directusUrl);
56
66
  try {
57
67
  if (flags.directusToken) {
58
- await sdk_2.api.loginWithToken(flags.directusToken);
68
+ await api.loginWithToken(flags.directusToken);
59
69
  }
60
70
  else if (flags.userEmail && flags.userPassword) {
61
- await sdk_2.api.login(flags.userEmail, flags.userPassword);
71
+ await api.login(flags.userEmail, flags.userPassword);
62
72
  }
63
- const response = await sdk_2.api.client.request((0, sdk_1.readMe)());
64
- core_1.ux.log(`-- Logged in as ${response.first_name} ${response.last_name}`);
73
+ const response = await api.client.request(readMe());
74
+ ux.stdout(`-- Logged in as ${response.first_name} ${response.last_name}`);
65
75
  }
66
76
  catch {
67
- (0, catch_error_1.default)('-- Unable to authenticate with the provided credentials. Please check your credentials.', {
77
+ catchError('-- Unable to authenticate with the provided credentials. Please check your credentials.', {
68
78
  fatal: true,
69
79
  });
70
80
  }
71
81
  }
72
- exports.initializeDirectusApi = initializeDirectusApi;
73
82
  /**
74
- * Validate the authentication flags
75
- * @param flags - The AuthFlags
76
- */
77
- function validateAuthFlags(flags) {
83
+ * Validate the authentication flags
84
+ * @param flags - The AuthFlags
85
+ * @returns {void} - Errors if the flags are invalid
86
+ */
87
+ export function validateAuthFlags(flags) {
78
88
  if (!flags.directusUrl) {
79
- core_1.ux.error('Directus URL is required.');
89
+ ux.error('Directus URL is required.');
80
90
  }
81
91
  if (!flags.directusToken && (!flags.userEmail || !flags.userPassword)) {
82
- core_1.ux.error('Either Directus token or email and password are required.');
92
+ ux.error('Either Directus token or email and password are required.');
83
93
  }
84
94
  }
85
- exports.validateAuthFlags = validateAuthFlags;
@@ -1,18 +1,16 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const core_1 = require("@oclif/core");
4
- const sdk_1 = require("../sdk");
5
- const logger_1 = require("../utils/logger");
1
+ import { ux } from '@oclif/core';
2
+ import { DirectusError } from '../sdk.js';
3
+ import { logger } from '../utils/logger.js';
6
4
  /**
7
5
  * Handles errors by formatting them and optionally logging to console and file.
8
6
  * @param error - The error to be handled.
9
7
  * @param options - Configuration options for error handling.
10
8
  * @returns void
11
9
  */
12
- function catchError(error, options = {}) {
10
+ export default function catchError(error, options = {}) {
13
11
  const { context = {}, fatal = false, logToFile = true } = options;
14
12
  let errorMessage;
15
- if (error instanceof sdk_1.DirectusError) {
13
+ if (error instanceof DirectusError) {
16
14
  errorMessage = error.message;
17
15
  }
18
16
  else if (error instanceof Error) {
@@ -29,13 +27,12 @@ function catchError(error, options = {}) {
29
27
  // Log the error message to the console with the appropriate color
30
28
  if (fatal) {
31
29
  // ux.error exits the process with a non-zero code
32
- core_1.ux.error(formattedMessage);
30
+ ux.error(formattedMessage);
33
31
  }
34
32
  else {
35
- core_1.ux.warn(formattedMessage);
33
+ ux.warn(formattedMessage);
36
34
  }
37
35
  if (logToFile) {
38
- logger_1.logger.log('error', errorMessage, context);
36
+ logger.log('error', errorMessage, context);
39
37
  }
40
38
  }
41
- exports.default = catchError;
@@ -1,12 +1,9 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const read_file_1 = tslib_1.__importDefault(require("../utils/read-file"));
5
- async function checkTemplate(dir) {
1
+ import readFile from '../utils/read-file.js';
2
+ export default async function checkTemplate(dir) {
6
3
  // Check for the collections,fields, and relations files
7
4
  try {
8
- const collections = (0, read_file_1.default)('collections', dir);
9
- const fields = (0, read_file_1.default)('fields', dir);
5
+ const collections = readFile('collections', dir);
6
+ const fields = readFile('fields', dir);
10
7
  const isCollectionsOk = collections.length > 0 && fields.length > 0;
11
8
  return isCollectionsOk;
12
9
  }
@@ -14,4 +11,3 @@ async function checkTemplate(dir) {
14
11
  console.error(error);
15
12
  }
16
13
  }
17
- exports.default = checkTemplate;
@@ -1,7 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.chunkArray = void 0;
4
- function chunkArray(array, size) {
1
+ export function chunkArray(array, size) {
5
2
  return Array.from({ length: Math.ceil(array.length / size) }, (_, index) => array.slice(index * size, (index + 1) * size));
6
3
  }
7
- exports.chunkArray = chunkArray;
@@ -1,16 +1,11 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ensureDirSync = exports.ensureDir = void 0;
4
- const node_fs_1 = require("node:fs");
5
- function ensureDir(dir) {
6
- if (!(0, node_fs_1.existsSync)(dir)) {
7
- (0, node_fs_1.mkdirSync)(dir, { recursive: true });
1
+ import { existsSync, mkdirSync } from 'node:fs';
2
+ export function ensureDir(dir) {
3
+ if (!existsSync(dir)) {
4
+ mkdirSync(dir, { recursive: true });
8
5
  }
9
6
  }
10
- exports.ensureDir = ensureDir;
11
- function ensureDirSync(dir) {
12
- if (!(0, node_fs_1.existsSync)(dir)) {
13
- (0, node_fs_1.mkdirSync)(dir, { recursive: true });
7
+ export function ensureDirSync(dir) {
8
+ if (!existsSync(dir)) {
9
+ mkdirSync(dir, { recursive: true });
14
10
  }
15
11
  }
16
- exports.ensureDirSync = ensureDirSync;
@@ -1,7 +1,5 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
1
  // Utility function to remove relationship data (arrays of integers or UUIDs) from system collection data. Used for when custom fields are added to system collections. The relational data should be populated when the actual data is loaded.
4
- function filterFields(dataArray, systemFields) {
2
+ export default function filterFields(dataArray, systemFields) {
5
3
  return dataArray.map(item => {
6
4
  for (const key of Object.keys(item)) {
7
5
  if (!systemFields.includes(key)) {
@@ -19,4 +17,3 @@ function filterFields(dataArray, systemFields) {
19
17
  return item;
20
18
  });
21
19
  }
22
- exports.default = filterFields;
@@ -1,5 +1,5 @@
1
1
  export default function getRoleIds(dir: string): Promise<{
2
- email: string;
2
+ email: any;
3
3
  legacyAdminRoleId: string;
4
4
  newAdminRoleId: string;
5
5
  }>;
@@ -1,16 +1,11 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const sdk_1 = require("@directus/sdk");
5
- const sdk_2 = require("../sdk");
6
- const read_file_1 = tslib_1.__importDefault(require("./read-file"));
7
- async function getRoleIds(dir) {
8
- var _a;
9
- const roles = (0, read_file_1.default)('roles', dir);
1
+ import { readMe } from '@directus/sdk';
2
+ import { api } from '../sdk.js';
3
+ import readFile from './read-file.js';
4
+ export default async function getRoleIds(dir) {
5
+ const roles = readFile('roles', dir);
10
6
  // Legacy admin role may be undefined if the admin role was renamed in the source Directus project.
11
- const legacyAdminRoleId = (_a = roles.find(role => role.name === 'Administrator')) === null || _a === void 0 ? void 0 : _a.id;
12
- const currentUser = await sdk_2.api.client.request((0, sdk_1.readMe)());
7
+ const legacyAdminRoleId = roles.find(role => role.name === 'Administrator')?.id;
8
+ const currentUser = await api.client.request(readMe());
13
9
  const newAdminRoleId = currentUser.role;
14
10
  return { email: currentUser.email, legacyAdminRoleId, newAdminRoleId };
15
11
  }
16
- exports.default = getRoleIds;