@sanity/runtime-cli 17.8.0 → 17.9.0-blueprinit.g14aaebd

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 (81) hide show
  1. package/README.md +28 -22
  2. package/dist/actions/blueprinit/manifest.d.ts +46 -0
  3. package/dist/actions/blueprinit/manifest.js +121 -0
  4. package/dist/actions/blueprinit/quote.d.ts +6 -0
  5. package/dist/actions/blueprinit/quote.js +8 -0
  6. package/dist/actions/blueprinit/studio.d.ts +6 -0
  7. package/dist/actions/blueprinit/studio.js +43 -0
  8. package/dist/actions/blueprinit/templates.d.ts +73 -0
  9. package/dist/actions/blueprinit/templates.js +138 -0
  10. package/dist/actions/blueprinit/versions.d.ts +8 -0
  11. package/dist/actions/blueprinit/versions.js +11 -0
  12. package/dist/actions/blueprinit/workspace.d.ts +27 -0
  13. package/dist/actions/blueprinit/workspace.js +145 -0
  14. package/dist/actions/blueprints/pre-deploy.js +2 -0
  15. package/dist/actions/blueprints/stacks.d.ts +3 -0
  16. package/dist/actions/blueprints/stacks.js +1 -0
  17. package/dist/actions/sanity/create-project.d.ts +19 -0
  18. package/dist/actions/sanity/create-project.js +32 -0
  19. package/dist/actions/sanity/datasets.d.ts +15 -0
  20. package/dist/actions/sanity/datasets.js +26 -0
  21. package/dist/actions/sanity/projects.d.ts +11 -0
  22. package/dist/actions/sanity/projects.js +48 -22
  23. package/dist/baseCommands.d.ts +6 -0
  24. package/dist/baseCommands.js +9 -1
  25. package/dist/commands/blueprints/stacks.d.ts +2 -1
  26. package/dist/commands/blueprints/stacks.js +14 -6
  27. package/dist/commands/functions/test.d.ts +1 -0
  28. package/dist/commands/functions/test.js +5 -0
  29. package/dist/commands/init.d.ts +21 -0
  30. package/dist/commands/init.js +82 -0
  31. package/dist/cores/blueprinit/adopt.d.ts +6 -0
  32. package/dist/cores/blueprinit/adopt.js +137 -0
  33. package/dist/cores/blueprinit/columns.d.ts +26 -0
  34. package/dist/cores/blueprinit/columns.js +27 -0
  35. package/dist/cores/blueprinit/finish.d.ts +15 -0
  36. package/dist/cores/blueprinit/finish.js +72 -0
  37. package/dist/cores/blueprinit/fresh.d.ts +3 -0
  38. package/dist/cores/blueprinit/fresh.js +219 -0
  39. package/dist/cores/blueprinit/naming.d.ts +27 -0
  40. package/dist/cores/blueprinit/naming.js +43 -0
  41. package/dist/cores/blueprinit/preview.d.ts +34 -0
  42. package/dist/cores/blueprinit/preview.js +110 -0
  43. package/dist/cores/blueprinit/project-choice.d.ts +28 -0
  44. package/dist/cores/blueprinit/project-choice.js +82 -0
  45. package/dist/cores/blueprinit/prompts.d.ts +13 -0
  46. package/dist/cores/blueprinit/prompts.js +42 -0
  47. package/dist/cores/blueprinit/results.d.ts +8 -0
  48. package/dist/cores/blueprinit/results.js +4 -0
  49. package/dist/cores/blueprinit/selection.d.ts +15 -0
  50. package/dist/cores/blueprinit/selection.js +90 -0
  51. package/dist/cores/blueprinit/stack-name.d.ts +39 -0
  52. package/dist/cores/blueprinit/stack-name.js +56 -0
  53. package/dist/cores/blueprinit/target.d.ts +33 -0
  54. package/dist/cores/blueprinit/target.js +80 -0
  55. package/dist/cores/blueprinit/types.d.ts +20 -0
  56. package/dist/cores/blueprinit/types.js +1 -0
  57. package/dist/cores/blueprinit.d.ts +7 -0
  58. package/dist/cores/blueprinit.js +64 -0
  59. package/dist/cores/blueprints/stacks.d.ts +8 -3
  60. package/dist/cores/blueprints/stacks.js +282 -85
  61. package/dist/cores/functions/test.d.ts +2 -19
  62. package/dist/cores/functions/test.js +63 -138
  63. package/dist/server/app.js +4 -6
  64. package/dist/server/static/components/payload-panel.js +1 -1
  65. package/dist/utils/display/intro.d.ts +6 -0
  66. package/dist/utils/display/intro.js +63 -0
  67. package/dist/utils/display/prompt.d.ts +4 -1
  68. package/dist/utils/display/prompt.js +16 -2
  69. package/dist/utils/functions/child-process-wrapper.js +3 -2
  70. package/dist/utils/functions/child-runtime/durable.d.ts +2 -2
  71. package/dist/utils/functions/child-runtime/durable.js +53 -3
  72. package/dist/utils/functions/durable-logs.d.ts +16 -0
  73. package/dist/utils/functions/durable-logs.js +52 -0
  74. package/dist/utils/functions/invoke/local.js +16 -8
  75. package/dist/utils/functions/invoke/resolve-invoke-type.d.ts +51 -0
  76. package/dist/utils/functions/invoke/resolve-invoke-type.js +131 -0
  77. package/dist/utils/types.d.ts +39 -6
  78. package/oclif.manifest.json +177 -5
  79. package/package.json +1 -1
  80. package/skills/blueprints-stacks.md +14 -2
  81. package/skills/init.md +199 -0
@@ -0,0 +1,7 @@
1
+ import type { BlueprinitFlags } from './blueprinit/types.js';
2
+ import type { CoreConfig, CoreResult } from './index.js';
3
+ export interface BlueprinitOptions extends CoreConfig {
4
+ dir?: string;
5
+ flags?: BlueprinitFlags;
6
+ }
7
+ export declare function blueprinitCore(options: BlueprinitOptions): Promise<CoreResult>;
@@ -0,0 +1,64 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { cwd } from 'node:process';
3
+ import { detectStudio } from '../actions/blueprinit/studio.js';
4
+ import { findBlueprintFile } from '../actions/blueprints/blueprint.js';
5
+ import { readConfigFile } from '../actions/blueprints/config.js';
6
+ import { validTokenOrErrorMessage } from '../utils/validated-token.js';
7
+ import { adoptFlow } from './blueprinit/adopt.js';
8
+ import { freshFlow } from './blueprinit/fresh.js';
9
+ export async function blueprinitCore(options) {
10
+ const { bin, log, flags = {}, dir = cwd() } = options;
11
+ try {
12
+ // findBlueprintFile answers with any file it is handed, so refuse a file target first.
13
+ if (existsSync(dir) && !statSync(dir).isDirectory()) {
14
+ return {
15
+ success: false,
16
+ error: `${dir} is not a directory.`,
17
+ suggestions: ['Pass a directory to initialize, or no argument to use this one.'],
18
+ };
19
+ }
20
+ const existingBlueprint = findBlueprintFile(dir);
21
+ if (existingBlueprint) {
22
+ const blueprintConfig = readConfigFile(existingBlueprint.blueprintFilePath);
23
+ if (!blueprintConfig?.stackId) {
24
+ return {
25
+ success: false,
26
+ error: `A Blueprint exists here (${existingBlueprint.fileName}), but it is not connected to a Stack.`,
27
+ suggestions: [`Finish setup with: npx ${bin} blueprints init`],
28
+ };
29
+ }
30
+ log(`A blueprint already exists here (${existingBlueprint.fileName}).`);
31
+ log('');
32
+ log('Use these instead:');
33
+ log(` npx ${bin} blueprints config --edit`);
34
+ log(` npx ${bin} blueprints doctor`);
35
+ return {
36
+ success: true,
37
+ json: { alreadyInitialized: true, blueprintFile: existingBlueprint.fileName },
38
+ };
39
+ }
40
+ const tokenCheck = await validTokenOrErrorMessage(log);
41
+ if (!tokenCheck.ok) {
42
+ return {
43
+ success: false,
44
+ error: 'No Sanity session found.',
45
+ suggestions: ['Sign in first: npx sanity login', 'Then run init again.'],
46
+ };
47
+ }
48
+ log('Setting up your Sanity workspace.');
49
+ log('');
50
+ const flowOptions = {
51
+ bin,
52
+ dir,
53
+ targetProvided: Boolean(options.dir),
54
+ flags,
55
+ log,
56
+ token: tokenCheck.value,
57
+ };
58
+ const studio = detectStudio(dir);
59
+ return studio ? await adoptFlow({ ...flowOptions, studio }) : await freshFlow(flowOptions);
60
+ }
61
+ catch (error) {
62
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
63
+ }
64
+ }
@@ -2,13 +2,18 @@ import type { ScopeType } from '../../utils/types.js';
2
2
  import type { CoreConfig, CoreResult } from '../index.js';
3
3
  export interface BlueprintStacksOptions extends CoreConfig {
4
4
  token: string;
5
- /** Scope to list Stacks for, resolved by the base command (flags > env > config). */
6
- scopeType: ScopeType;
7
- scopeId: string;
5
+ /**
6
+ * Scope to list Stacks for, resolved by the base command (flags > env > config).
7
+ * Prompted for when absent.
8
+ */
9
+ scopeType?: ScopeType;
10
+ scopeId?: string;
8
11
  /** Locally-configured Stack ID, used only to highlight the current Stack in listings. */
9
12
  localStackId?: string;
10
13
  flags: {
14
+ all?: boolean;
11
15
  'include-projects'?: boolean;
16
+ json?: boolean;
12
17
  verbose?: boolean;
13
18
  };
14
19
  }
@@ -1,39 +1,78 @@
1
1
  import { listStacks } from '../../actions/blueprints/stacks.js';
2
- import { listProjects } from '../../actions/sanity/projects.js';
2
+ import { listOrganizations, listProjects, } from '../../actions/sanity/projects.js';
3
+ import { CI_SETUP_DOCS_URL } from '../../constants.js';
3
4
  import { formatStacksListing } from '../../utils/display/blueprints-formatting.js';
4
5
  import { capitalize, niceId, warn } from '../../utils/display/presenters.js';
6
+ import { promptForOrganization, promptForProjectInOrg, promptForScope, promptForScopeRecovery, } from '../../utils/display/prompt.js';
7
+ import { isInteractive } from '../../utils/interactive.js';
5
8
  import { styleText } from '../../utils/style-text.js';
6
- /** Max projects to query for stacks during --include-projects */
9
+ /** Max projects to query for stacks within one organization */
7
10
  const PROJECT_LIMIT = 50;
11
+ /** Max projects to query for stacks across every organization */
12
+ const ALL_PROJECTS_LIMIT = 200;
13
+ /** Stack listings in flight while querying many scopes */
14
+ const SCOPE_CONCURRENCY = 5;
8
15
  export async function blueprintStacksCore(options) {
9
- const { log, token, scopeType, scopeId, localStackId: blueprintStackId, flags } = options;
10
- const { 'include-projects': includeProjects = false } = flags;
11
- if (includeProjects && scopeType === 'organization') {
12
- return deepListStacks({ organizationId: scopeId, token, log, blueprintStackId });
13
- }
16
+ const { bin, log, token, localStackId: blueprintStackId, flags } = options;
17
+ const { all = false, 'include-projects': includeProjects = false, json = false } = flags;
14
18
  try {
15
- const spinner = log.ora('Fetching Stacks...').start();
16
- const { ok, stacks, error } = await listStacks({ token, scopeType, scopeId }, log);
17
- if (!ok) {
18
- spinner.fail('Failed to list Stacks');
19
- const suggestions = [];
20
- if (error && /access|permission|forbidden/i.test(error)) {
21
- suggestions.push('Verify you have access to this organization or project.', `Try a different scope with --project-id or --organization-id.`);
19
+ if (all)
20
+ return await listStacksEverywhere({ token, log, blueprintStackId });
21
+ let { scopeType, scopeId } = options;
22
+ let displayName;
23
+ let promptedForScope = false;
24
+ let hasAlternativeScope = false;
25
+ while (true) {
26
+ if (!scopeType || !scopeId) {
27
+ if (!isInteractive || json)
28
+ return missingScopeResult(bin);
29
+ const chosen = await chooseScope({ token, log });
30
+ scopeType = chosen.scopeType;
31
+ scopeId = chosen.scopeId;
32
+ displayName = chosen.displayName;
33
+ hasAlternativeScope = chosen.hasAlternativeScope;
34
+ promptedForScope = true;
22
35
  }
23
- return {
24
- success: false,
25
- error: error || 'Failed to list stacks',
26
- suggestions: suggestions.length ? suggestions : undefined,
27
- };
28
- }
29
- spinner.stop().clear();
30
- if (!stacks || stacks.length === 0) {
31
- log('No stacks found');
32
- return { success: true };
36
+ if (includeProjects && scopeType === 'organization') {
37
+ return await listStacksAcrossOrganization({
38
+ organizationId: scopeId,
39
+ token,
40
+ log,
41
+ blueprintStackId,
42
+ });
43
+ }
44
+ const spinner = log.ora('Fetching Stacks...').start();
45
+ const result = await listStacks({ token, scopeType, scopeId }, log);
46
+ if (!result.ok) {
47
+ if (promptedForScope && hasAlternativeScope && result.response?.status === 403) {
48
+ spinner.stop().clear();
49
+ log(warn(`Your account can see ${scopeTargetLabel({ scopeType, scopeId, displayName })}, but cannot read its Blueprint Stacks.`));
50
+ const recovery = await promptForScopeRecovery();
51
+ if (recovery === 'retry') {
52
+ scopeType = undefined;
53
+ scopeId = undefined;
54
+ displayName = undefined;
55
+ hasAlternativeScope = false;
56
+ continue;
57
+ }
58
+ }
59
+ else {
60
+ spinner.fail('Failed to list Stacks');
61
+ }
62
+ return listStacksFailure(result.error, result.response?.status);
63
+ }
64
+ spinner.stop().clear();
65
+ if (result.stacks.length === 0) {
66
+ log('No stacks found');
67
+ return { success: true, json: { stacks: [], scopeType, scopeId } };
68
+ }
69
+ printStackGroups({
70
+ groups: [{ scopeType, scopeId, displayName, stacks: result.stacks }],
71
+ log,
72
+ blueprintStackId,
73
+ });
74
+ return { success: true, json: { stacks: result.stacks, scopeType, scopeId } };
33
75
  }
34
- log(`${styleText('bold', capitalize(scopeType))} ${niceId(scopeId)} ${styleText('bold', 'Stacks')}:\n`);
35
- log(formatStacksListing(stacks, blueprintStackId));
36
- return { success: true, json: { stacks, scopeType, scopeId } };
37
76
  }
38
77
  catch (error) {
39
78
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -41,71 +80,229 @@ export async function blueprintStacksCore(options) {
41
80
  return { success: false, error: errorMessage };
42
81
  }
43
82
  }
44
- async function deepListStacks(options) {
83
+ function listStacksFailure(error, status) {
84
+ return {
85
+ success: false,
86
+ error: error || 'Failed to list stacks',
87
+ suggestions: status === 403
88
+ ? [
89
+ 'Ask an administrator to grant you read access to Blueprint Stacks for this organization or project.',
90
+ 'Try a different scope with --project-id or --organization-id.',
91
+ ]
92
+ : undefined,
93
+ };
94
+ }
95
+ function missingScopeResult(bin) {
96
+ return {
97
+ success: false,
98
+ error: 'Missing scope: provide --project-id or --organization-id.',
99
+ suggestions: [
100
+ `Run \`${bin} blueprints stacks --all\` to list Stacks for every organization and project.`,
101
+ 'Set SANITY_PROJECT_ID or SANITY_ORGANIZATION_ID when no terminal is available.',
102
+ ],
103
+ ref: CI_SETUP_DOCS_URL,
104
+ };
105
+ }
106
+ /** Organization, then project when the user picks project scope. */
107
+ async function chooseScope(options) {
108
+ const { token, log } = options;
109
+ const orgResult = await promptForOrganization({ token, logger: log });
110
+ if (typeof orgResult === 'symbol')
111
+ throw new Error('Unexpected back navigation');
112
+ const scopeType = await promptForScope({
113
+ hasProjects: orgResult.projects.length > 0,
114
+ message: 'Which Stacks would you like to list?',
115
+ });
116
+ if (typeof scopeType === 'symbol')
117
+ throw new Error('Unexpected back navigation');
118
+ if (scopeType === 'organization') {
119
+ const { id, name } = orgResult.organization;
120
+ return {
121
+ scopeType,
122
+ scopeId: id,
123
+ displayName: name,
124
+ hasAlternativeScope: orgResult.wasPrompted || orgResult.projects.length > 0,
125
+ };
126
+ }
127
+ const project = await promptForProjectInOrg({ projects: orgResult.projects, logger: log });
128
+ if (typeof project === 'symbol')
129
+ throw new Error('Unexpected back navigation');
130
+ return {
131
+ scopeType,
132
+ scopeId: project.projectId,
133
+ displayName: project.displayName,
134
+ // The containing organization is another possible scope even when it has no other projects.
135
+ hasAlternativeScope: true,
136
+ };
137
+ }
138
+ async function listStacksAcrossOrganization(options) {
45
139
  const { organizationId, token, log, blueprintStackId } = options;
46
- const allStacks = [];
47
140
  const spinner = log.ora('Fetching Stacks...').start();
48
- try {
49
- // 1. Org-scoped stacks
50
- const orgResult = await listStacks({ token, scopeType: 'organization', scopeId: organizationId }, log);
51
- const orgStacks = orgResult.ok ? orgResult.stacks : [];
52
- // 2. Get projects in the organization
53
- const projectsResult = await listProjects({ token, organizationId, logger: log });
54
- if (!projectsResult.ok) {
55
- spinner.fail('Failed to list projects');
56
- return { success: false, error: projectsResult.error || 'Failed to list projects' };
141
+ const projectsResult = await listProjects({ token, organizationId, logger: log });
142
+ if (!projectsResult.ok) {
143
+ spinner.fail('Failed to list projects');
144
+ return { success: false, error: projectsResult.error || 'Failed to list projects' };
145
+ }
146
+ const projects = projectsResult.projects;
147
+ const targets = [
148
+ { scopeType: 'organization', scopeId: organizationId },
149
+ ...projectTargets(projects.slice(0, PROJECT_LIMIT)),
150
+ ];
151
+ const { groups, failures, successfulScopes } = await collectStackGroups({
152
+ targets,
153
+ token,
154
+ log,
155
+ onProgress: (completed, total) => {
156
+ spinner.text = `Fetching Stacks... (${completed}/${total})`;
157
+ },
158
+ });
159
+ if (successfulScopes === 0 && failures.length > 0) {
160
+ spinner.fail('Failed to list Stacks');
161
+ return listStacksFailure(failures[0].error, failures[0].status);
162
+ }
163
+ spinner.stop().clear();
164
+ const stacks = groups.flatMap((group) => group.stacks);
165
+ if (stacks.length > 0)
166
+ printStackGroups({ groups, log, blueprintStackId });
167
+ else
168
+ log('No stacks found');
169
+ const organizationFailure = failures.find(({ target }) => target.scopeType === 'organization');
170
+ if (organizationFailure) {
171
+ log(warn(`Could not read organization-scoped Stacks: ${organizationFailure.error}`));
172
+ }
173
+ const projectFailures = failures.filter(({ target }) => target.scopeType === 'project');
174
+ if (projectFailures.length > 0) {
175
+ const projectCount = targets.filter(({ scopeType }) => scopeType === 'project').length;
176
+ log(warn(`Could not read Stacks for ${projectFailures.length} of ${projectCount} projects.`));
177
+ for (const { target, error } of projectFailures) {
178
+ log.verbose(`Project ${target.scopeId}: ${error}`);
57
179
  }
58
- const projects = projectsResult.projects;
59
- const totalProjects = projects.length;
60
- const cappedProjects = projects.slice(0, PROJECT_LIMIT);
61
- // 3. Fetch stacks for each project
62
- const projectGroups = [];
63
- for (let i = 0; i < cappedProjects.length; i++) {
64
- const project = cappedProjects[i];
65
- spinner.text = `Fetching Stacks... (project ${i + 1}/${cappedProjects.length})`;
66
- const result = await listStacks({ token, scopeType: 'project', scopeId: project.id }, log);
67
- if (result.ok && result.stacks.length > 0) {
68
- projectGroups.push({
69
- projectId: project.id,
70
- displayName: project.displayName,
71
- stacks: result.stacks,
180
+ }
181
+ if (projects.length > PROJECT_LIMIT)
182
+ log(projectLimitWarning(projects.length, PROJECT_LIMIT));
183
+ return { success: true, json: { stacks, scopeType: 'organization', scopeId: organizationId } };
184
+ }
185
+ /** Every organization and project the token can reach, skipping the scopes it cannot read. */
186
+ async function listStacksEverywhere(options) {
187
+ const { token, log, blueprintStackId } = options;
188
+ const spinner = log.ora('Finding organizations and projects...').start();
189
+ const [orgsResult, projectsResult] = await Promise.all([
190
+ listOrganizations({ token, logger: log }),
191
+ listProjects({ token, logger: log }),
192
+ ]);
193
+ if (!orgsResult.ok && !projectsResult.ok) {
194
+ spinner.fail('Failed to list organizations and projects');
195
+ return {
196
+ success: false,
197
+ error: orgsResult.error || projectsResult.error || 'Failed to list organizations',
198
+ };
199
+ }
200
+ const discoveryWarnings = [];
201
+ if (!orgsResult.ok) {
202
+ discoveryWarnings.push(`Could not list organizations: ${orgsResult.error || 'unknown error'}`);
203
+ }
204
+ if (!projectsResult.ok) {
205
+ discoveryWarnings.push(`Could not list projects: ${projectsResult.error || 'unknown error'}`);
206
+ }
207
+ const organizations = orgsResult.ok ? orgsResult.organizations : [];
208
+ const projects = projectsResult.ok ? projectsResult.projects : [];
209
+ const targets = buildScopeTargets(organizations, projects.slice(0, ALL_PROJECTS_LIMIT));
210
+ spinner.text = 'Fetching Stacks...';
211
+ const { groups, failures, successfulScopes } = await collectStackGroups({
212
+ targets,
213
+ token,
214
+ log,
215
+ onProgress: (completed, total) => {
216
+ spinner.text = `Fetching Stacks... (${completed}/${total})`;
217
+ },
218
+ });
219
+ if (targets.length > 0 && successfulScopes === 0) {
220
+ spinner.fail('Failed to list Stacks');
221
+ return listStacksFailure(failures[0]?.error, failures[0]?.status);
222
+ }
223
+ spinner.stop().clear();
224
+ const stacks = groups.flatMap((group) => group.stacks);
225
+ if (stacks.length > 0)
226
+ printStackGroups({ groups, log, blueprintStackId });
227
+ else if (targets.length === 0)
228
+ log('No organizations or projects found');
229
+ else
230
+ log('No stacks found');
231
+ for (const message of discoveryWarnings)
232
+ log(warn(message));
233
+ if (projects.length > ALL_PROJECTS_LIMIT) {
234
+ log(projectLimitWarning(projects.length, ALL_PROJECTS_LIMIT));
235
+ }
236
+ if (failures.length > 0) {
237
+ log(warn(`Could not read Stacks for ${failures.length} of ${targets.length} scopes.`));
238
+ for (const { target, error } of failures) {
239
+ log.verbose(`${capitalize(target.scopeType)} ${target.scopeId}: ${error}`);
240
+ }
241
+ }
242
+ return { success: true, json: { stacks } };
243
+ }
244
+ async function collectStackGroups(options) {
245
+ const { targets, token, log, onProgress } = options;
246
+ const groups = [];
247
+ const failures = [];
248
+ let completed = 0;
249
+ let successfulScopes = 0;
250
+ for (let start = 0; start < targets.length; start += SCOPE_CONCURRENCY) {
251
+ const batch = await Promise.all(targets.slice(start, start + SCOPE_CONCURRENCY).map(async (target) => {
252
+ const { scopeType, scopeId } = target;
253
+ const result = await listStacks({ token, scopeType, scopeId }, log);
254
+ completed += 1;
255
+ onProgress?.(completed, targets.length);
256
+ return { target, result };
257
+ }));
258
+ for (const { target, result } of batch) {
259
+ if (!result.ok) {
260
+ failures.push({
261
+ target,
262
+ error: result.error || 'Failed to list stacks',
263
+ status: result.response?.status,
72
264
  });
73
- allStacks.push(...result.stacks);
74
265
  }
75
- else if (!result.ok) {
76
- throw new Error(result.error);
266
+ else {
267
+ successfulScopes += 1;
268
+ if (result.stacks.length > 0)
269
+ groups.push({ ...target, stacks: result.stacks });
77
270
  }
78
271
  }
79
- spinner.stop().clear();
80
- // 4. Print results
81
- if (orgStacks.length > 0) {
82
- log(`${styleText('bold', 'Organization')} ${niceId(organizationId)} ${styleText('bold', 'Stacks')}:\n`);
83
- log(formatStacksListing(orgStacks, blueprintStackId));
84
- if (projectGroups.length > 0)
85
- log(''); // blank line between sections
86
- }
87
- for (const group of projectGroups) {
88
- log(`${styleText('bold', 'Project')} "${group.displayName}" ${niceId(group.projectId)} ${styleText('bold', 'Stacks')}:`);
89
- log(formatStacksListing(group.stacks, blueprintStackId));
90
- log('');
91
- }
92
- if (totalProjects > PROJECT_LIMIT) {
93
- log(warn(`Organization has ${totalProjects} projects, only checked the first ${PROJECT_LIMIT}.`));
94
- }
95
- if (orgStacks.length === 0 && allStacks.length === 0) {
96
- log('No stacks found');
97
- return { success: true };
98
- }
99
- allStacks.push(...orgStacks);
100
- return {
101
- success: true,
102
- json: { stacks: allStacks, scopeType: 'organization', scopeId: organizationId },
103
- };
104
272
  }
105
- catch (error) {
106
- spinner.stop().clear();
107
- const errorMessage = error instanceof Error ? error.message : String(error);
108
- log.error(`Error: ${errorMessage}`);
109
- return { success: false, error: errorMessage };
273
+ return { groups, failures, successfulScopes };
274
+ }
275
+ function buildScopeTargets(organizations, projects) {
276
+ const organizationIds = new Set(organizations.map(({ id }) => id));
277
+ const targets = [];
278
+ for (const { id, name } of organizations) {
279
+ targets.push({ scopeType: 'organization', scopeId: id, displayName: name });
280
+ targets.push(...projectTargets(projects.filter((p) => p.organizationId === id)));
110
281
  }
282
+ targets.push(...projectTargets(projects.filter((p) => !organizationIds.has(p.organizationId))));
283
+ return targets;
284
+ }
285
+ function projectTargets(projects) {
286
+ return projects.map(({ id, displayName }) => ({
287
+ scopeType: 'project',
288
+ scopeId: id,
289
+ displayName,
290
+ }));
291
+ }
292
+ function scopeTargetLabel({ scopeType, scopeId, displayName }) {
293
+ const name = displayName ? ` "${displayName}"` : '';
294
+ return `${scopeType}${name} ${niceId(scopeId)}`;
295
+ }
296
+ function printStackGroups(options) {
297
+ const { groups, log, blueprintStackId } = options;
298
+ groups.forEach((group, index) => {
299
+ const name = group.displayName ? ` "${group.displayName}"` : '';
300
+ if (index > 0)
301
+ log('');
302
+ log(`${styleText('bold', capitalize(group.scopeType))}${name} ${niceId(group.scopeId)} ${styleText('bold', 'Stacks')}:\n`);
303
+ log(formatStacksListing(group.stacks, blueprintStackId));
304
+ });
305
+ }
306
+ function projectLimitWarning(total, limit) {
307
+ return warn(`Found ${total} projects, only checked the first ${limit}.`);
111
308
  }
@@ -1,29 +1,12 @@
1
1
  import type { ReadBlueprintResult } from '../../actions/blueprints/blueprint.js';
2
+ import { type FunctionTestFlags } from '../../utils/types.js';
2
3
  import type { CoreConfig, CoreResult } from '../index.js';
3
4
  export interface FunctionTestOptions extends CoreConfig {
4
5
  blueprint: ReadBlueprintResult;
5
6
  args: {
6
7
  name: string | undefined;
7
8
  };
8
- flags: {
9
- data?: string;
10
- event?: string;
11
- file?: string;
12
- timeout?: number;
13
- api?: string;
14
- dataset?: string;
15
- 'project-id'?: string;
16
- 'organization-id'?: string;
17
- 'document-id'?: string;
18
- 'with-user-token'?: boolean;
19
- 'data-before'?: string;
20
- 'data-after'?: string;
21
- 'file-before'?: string;
22
- 'file-after'?: string;
23
- 'document-id-before'?: string;
24
- 'document-id-after'?: string;
25
- 'media-library-id'?: string;
26
- };
9
+ flags: FunctionTestFlags;
27
10
  error: (message: string, options: object) => void;
28
11
  helpText: string;
29
12
  }