@yoonion/mimi-seed-mcp 0.23.1 → 0.23.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 (50) hide show
  1. package/README.md +1 -1
  2. package/assets/agent-guide.md +20 -2
  3. package/dist/appstore/app-info-policy.d.ts +27 -0
  4. package/dist/appstore/app-info-policy.js +104 -0
  5. package/dist/appstore/app-info.d.ts +19 -0
  6. package/dist/appstore/app-info.js +68 -0
  7. package/dist/appstore/apps.d.ts +1 -5
  8. package/dist/appstore/apps.js +12 -37
  9. package/dist/appstore/asset-library-write.d.ts +39 -0
  10. package/dist/appstore/asset-library-write.js +282 -0
  11. package/dist/appstore/asset-library.d.ts +28 -0
  12. package/dist/appstore/asset-library.js +197 -0
  13. package/dist/appstore/client.d.ts +4 -3
  14. package/dist/appstore/declarations.js +11 -14
  15. package/dist/appstore/messages.js +4 -4
  16. package/dist/appstore/previews.js +3 -29
  17. package/dist/appstore/read-response.d.ts +27 -0
  18. package/dist/appstore/read-response.js +38 -0
  19. package/dist/appstore/release-target.d.ts +54 -0
  20. package/dist/appstore/release-target.js +124 -0
  21. package/dist/appstore/release.js +100 -47
  22. package/dist/appstore/review-preview.d.ts +19 -0
  23. package/dist/appstore/review-preview.js +141 -0
  24. package/dist/appstore/review-submission.d.ts +2 -28
  25. package/dist/appstore/review-submission.js +14 -59
  26. package/dist/appstore/screenshots.d.ts +1 -0
  27. package/dist/appstore/screenshots.js +60 -4
  28. package/dist/appstore/upload-parts.d.ts +11 -0
  29. package/dist/appstore/upload-parts.js +29 -0
  30. package/dist/appstore/versions.d.ts +9 -0
  31. package/dist/appstore/versions.js +15 -14
  32. package/dist/checks/appstore-submission.d.ts +75 -0
  33. package/dist/checks/appstore-submission.js +56 -0
  34. package/dist/checks/plan.d.ts +58 -2
  35. package/dist/checks/plan.js +103 -106
  36. package/dist/checks/release-readiness.d.ts +195 -0
  37. package/dist/checks/release-readiness.js +58 -0
  38. package/dist/checks/release-status.d.ts +76 -0
  39. package/dist/checks/release-status.js +72 -0
  40. package/dist/checks/risks.d.ts +40 -14
  41. package/dist/checks/risks.js +283 -231
  42. package/dist/lib/tool-registrar.d.ts +1 -1
  43. package/dist/lib/tool-registrar.js +5 -5
  44. package/dist/playstore/edits.js +25 -2
  45. package/dist/registers/appstore/media.js +69 -24
  46. package/dist/registers/appstore/review-submission.js +8 -4
  47. package/dist/registers/checks.js +34 -94
  48. package/dist/registers/playstore.js +5 -4
  49. package/package.json +1 -1
  50. package/tool-manifest.json +5 -2
@@ -0,0 +1,27 @@
1
+ import { z } from 'zod';
2
+ export declare const appStoreResourceRef: z.ZodObject<{
3
+ id: z.ZodString;
4
+ type: z.ZodString;
5
+ }, z.core.$strip>;
6
+ export declare const appStoreToOne: z.ZodObject<{
7
+ data: z.ZodNullable<z.ZodObject<{
8
+ id: z.ZodString;
9
+ type: z.ZodString;
10
+ }, z.core.$strip>>;
11
+ }, z.core.$strip>;
12
+ export declare function includedAppStoreResource<T>(included: readonly unknown[] | null | undefined, ref: z.infer<typeof appStoreResourceRef>, schema: z.ZodType<T>): T | undefined;
13
+ export declare const appStorePagination: z.ZodObject<{
14
+ links: z.ZodOptional<z.ZodNullable<z.ZodObject<{
15
+ next: z.ZodOptional<z.ZodNullable<z.ZodString>>;
16
+ }, z.core.$strip>>>;
17
+ meta: z.ZodOptional<z.ZodObject<{
18
+ paging: z.ZodOptional<z.ZodObject<{
19
+ total: z.ZodOptional<z.ZodNumber>;
20
+ limit: z.ZodOptional<z.ZodNumber>;
21
+ nextCursor: z.ZodOptional<z.ZodNullable<z.ZodString>>;
22
+ }, z.core.$strip>>;
23
+ }, z.core.$strip>>;
24
+ }, z.core.$strip>;
25
+ export declare function appStoreNextPagePath(path: string, next: string): string;
26
+ export declare function pageIsIncomplete(page: z.infer<typeof appStorePagination>, count: number): boolean;
27
+ export declare function getAppStoreResponse<T>(schema: z.ZodType<T>, path: string, params?: Record<string, string>): Promise<T>;
@@ -0,0 +1,38 @@
1
+ import { z } from 'zod';
2
+ import { apiGet } from './client.js';
3
+ import { V1_BASE } from './http.js';
4
+ export const appStoreResourceRef = z.object({ id: z.string().min(1), type: z.string().min(1) });
5
+ export const appStoreToOne = z.object({ data: appStoreResourceRef.nullable() });
6
+ export function includedAppStoreResource(included, ref, schema) {
7
+ const matches = included?.filter((resource) => resource !== null && typeof resource === 'object'
8
+ && 'id' in resource && resource.id === ref.id && 'type' in resource && resource.type === ref.type);
9
+ return matches?.length === 1 ? schema.safeParse(matches[0]).data : undefined;
10
+ }
11
+ export const appStorePagination = z.object({
12
+ links: z.object({ next: z.string().nullish() }).nullish(),
13
+ meta: z.object({ paging: z.object({
14
+ total: z.number().int().nonnegative().optional(),
15
+ limit: z.number().int().nonnegative().optional(),
16
+ nextCursor: z.string().nullish(),
17
+ }).optional() }).optional(),
18
+ });
19
+ export function appStoreNextPagePath(path, next) {
20
+ const endpoint = new URL(`${V1_BASE}${path}`);
21
+ const url = new URL(next, endpoint);
22
+ if (url.origin !== endpoint.origin || url.pathname !== endpoint.pathname
23
+ || url.username || url.password || url.hash || !url.search) {
24
+ throw new Error('App Store Connect의 다음 페이지 링크가 요청한 리소스와 일치하지 않습니다.');
25
+ }
26
+ return `${path}${url.search}`;
27
+ }
28
+ export function pageIsIncomplete(page, count) {
29
+ return Boolean(page.links?.next || page.meta?.paging?.nextCursor) || (page.meta?.paging?.total ?? 0) > count;
30
+ }
31
+ export async function getAppStoreResponse(schema, path, params) {
32
+ const response = schema.safeParse(await apiGet(path, params));
33
+ if (!response.success) {
34
+ const field = response.error.issues[0]?.path.join('.') || '응답 본문';
35
+ throw new Error(`App Store Connect 응답 형식 오류 (${field}).`);
36
+ }
37
+ return response.data;
38
+ }
@@ -0,0 +1,54 @@
1
+ import { z } from 'zod';
2
+ export declare const appStorePlatformSchema: z.ZodEnum<{
3
+ IOS: "IOS";
4
+ MAC_OS: "MAC_OS";
5
+ TV_OS: "TV_OS";
6
+ VISION_OS: "VISION_OS";
7
+ }>;
8
+ export type AppStorePlatform = z.infer<typeof appStorePlatformSchema>;
9
+ declare const processingState: z.ZodEnum<{
10
+ PROCESSING: "PROCESSING";
11
+ FAILED: "FAILED";
12
+ INVALID: "INVALID";
13
+ VALID: "VALID";
14
+ }>;
15
+ export type AppStoreBuildReadiness = {
16
+ status: 'missing';
17
+ } | {
18
+ status: 'unknown';
19
+ detail: string;
20
+ } | {
21
+ status: 'ready' | 'not-ready';
22
+ id: string;
23
+ processingState: z.infer<typeof processingState>;
24
+ buildNumber?: string;
25
+ };
26
+ export interface AppStoreVersionCandidate {
27
+ id: string;
28
+ versionString?: string;
29
+ state: string;
30
+ platform: AppStorePlatform;
31
+ appStoreState?: string;
32
+ releaseType?: string;
33
+ createdDate?: string;
34
+ linkedBuildId?: string;
35
+ build?: AppStoreBuildReadiness;
36
+ }
37
+ type VersionSelection = {
38
+ status: 'selected';
39
+ version: AppStoreVersionCandidate;
40
+ } | {
41
+ status: 'missing';
42
+ } | {
43
+ status: 'ambiguous';
44
+ } | {
45
+ status: 'incomplete';
46
+ };
47
+ export declare function selectEditableAppStoreVersion(appId: string, filters?: {
48
+ versionId?: string;
49
+ versionString?: string;
50
+ }): Promise<VersionSelection>;
51
+ export declare function selectAppStoreVersionForStatus(appId: string, versionString: string, platform?: AppStorePlatform): Promise<VersionSelection>;
52
+ /** Resolve the selected version's build without an API request when included data is complete. */
53
+ export declare function resolveAppStoreVersionBuild(version: AppStoreVersionCandidate): Promise<AppStoreBuildReadiness>;
54
+ export {};
@@ -0,0 +1,124 @@
1
+ import { z } from 'zod';
2
+ import { encodePathSegment } from '../lib/url-path.js';
3
+ import { isNotFound } from './http.js';
4
+ import { appStorePagination, getAppStoreResponse, includedAppStoreResource, pageIsIncomplete } from './read-response.js';
5
+ const editableStates = ['PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'METADATA_REJECTED', 'REJECTED'];
6
+ const versionPage = appStorePagination.extend({
7
+ data: z.array(z.object({
8
+ id: z.string().min(1),
9
+ type: z.literal('appStoreVersions').optional(),
10
+ attributes: z.object({
11
+ versionString: z.string().nullish(),
12
+ appVersionState: z.string().nullish(),
13
+ appStoreState: z.string().nullish(),
14
+ platform: z.string().nullish(),
15
+ releaseType: z.string().nullish(),
16
+ createdDate: z.string().nullish(),
17
+ }).nullish(),
18
+ relationships: z.object({ build: z.unknown().optional() }).nullish(),
19
+ })),
20
+ included: z.array(z.unknown()).nullish(),
21
+ });
22
+ export const appStorePlatformSchema = z.enum(['IOS', 'MAC_OS', 'TV_OS', 'VISION_OS']);
23
+ const buildReference = z.object({ id: z.string().min(1), type: z.literal('builds') });
24
+ const buildRelationship = z.object({ data: buildReference.nullable() });
25
+ const processingState = z.enum(['PROCESSING', 'FAILED', 'INVALID', 'VALID']);
26
+ const buildResource = buildReference.extend({
27
+ attributes: z.object({ processingState, version: z.string().nullish() }).nullish(),
28
+ });
29
+ const buildResponse = z.object({ data: buildResource.nullable() });
30
+ function buildReadiness(build) {
31
+ const state = build.attributes?.processingState;
32
+ if (!state)
33
+ return undefined;
34
+ return {
35
+ status: state === 'VALID' ? 'ready' : 'not-ready',
36
+ id: build.id,
37
+ processingState: state,
38
+ buildNumber: build.attributes?.version ?? undefined,
39
+ };
40
+ }
41
+ export function selectEditableAppStoreVersion(appId, filters = {}) {
42
+ return selectVersion(appId, filters, true);
43
+ }
44
+ export function selectAppStoreVersionForStatus(appId, versionString, platform) {
45
+ return selectVersion(appId, { versionString, platform }, false);
46
+ }
47
+ async function selectVersion(appId, filters, editableOnly) {
48
+ const { versionId, versionString, platform } = filters;
49
+ const fields = 'versionString,platform,appVersionState,build';
50
+ const page = await getAppStoreResponse(versionPage, `/apps/${encodePathSegment(appId)}/appStoreVersions`, {
51
+ ...(editableOnly ? { 'filter[appVersionState]': editableStates.join(',') } : {}),
52
+ ...(versionId ? { 'filter[id]': versionId } : {}),
53
+ ...(versionString ? { 'filter[versionString]': versionString } : {}),
54
+ ...(platform ? { 'filter[platform]': platform } : {}),
55
+ 'fields[appStoreVersions]': editableOnly ? fields : `${fields},appStoreState,releaseType,createdDate`,
56
+ 'fields[builds]': 'processingState,version',
57
+ include: 'build',
58
+ limit: versionId ? '1' : '5',
59
+ });
60
+ const candidates = [];
61
+ let incomplete = pageIsIncomplete(page, page.data.length);
62
+ for (const row of page.data) {
63
+ const { attributes } = row;
64
+ const version = attributes?.versionString ?? undefined;
65
+ const state = attributes?.appVersionState ?? attributes?.appStoreState ?? undefined;
66
+ if ((versionId && versionId !== row.id) || (versionString && version && versionString !== version)
67
+ || (editableOnly && state && !editableStates.includes(state)))
68
+ continue;
69
+ const rowPlatform = appStorePlatformSchema.safeParse(attributes?.platform);
70
+ if (rowPlatform.success && platform && platform !== rowPlatform.data)
71
+ continue;
72
+ if (!state || !rowPlatform.success || (versionString && !version)) {
73
+ incomplete = true;
74
+ continue;
75
+ }
76
+ const linkage = buildRelationship.safeParse(row.relationships?.build);
77
+ const linkedBuildId = linkage.success ? linkage.data.data?.id : undefined;
78
+ const embedded = linkage.data?.data && includedAppStoreResource(page.included, linkage.data.data, buildResource);
79
+ candidates.push({
80
+ id: row.id,
81
+ versionString: version,
82
+ state,
83
+ platform: rowPlatform.data,
84
+ appStoreState: attributes?.appStoreState ?? undefined,
85
+ releaseType: attributes?.releaseType ?? undefined,
86
+ createdDate: attributes?.createdDate ?? undefined,
87
+ linkedBuildId,
88
+ build: linkage.success && linkage.data.data === null
89
+ ? { status: 'missing' }
90
+ : embedded ? buildReadiness(embedded) : undefined,
91
+ });
92
+ }
93
+ if (candidates.length > 1)
94
+ return { status: 'ambiguous' };
95
+ if (incomplete)
96
+ return { status: 'incomplete' };
97
+ const version = candidates[0];
98
+ return version ? { status: 'selected', version } : { status: 'missing' };
99
+ }
100
+ /** Resolve the selected version's build without an API request when included data is complete. */
101
+ export async function resolveAppStoreVersionBuild(version) {
102
+ if (version.build)
103
+ return version.build;
104
+ const missing = version.linkedBuildId
105
+ ? { status: 'unknown', detail: '버전 목록의 빌드 연결과 상세 조회 결과가 일치하지 않습니다.' }
106
+ : { status: 'missing' };
107
+ try {
108
+ const { data } = await getAppStoreResponse(buildResponse, `/appStoreVersions/${encodePathSegment(version.id)}/build`, {
109
+ 'fields[builds]': 'processingState,version',
110
+ });
111
+ if (!data)
112
+ return missing;
113
+ if (version.linkedBuildId && data.id !== version.linkedBuildId) {
114
+ return { status: 'unknown', detail: '버전 목록과 상세 조회에서 서로 다른 빌드 ID가 반환되었습니다.' };
115
+ }
116
+ return buildReadiness(data)
117
+ ?? { status: 'unknown', detail: '연결된 빌드의 처리 상태가 응답에 없습니다.' };
118
+ }
119
+ catch (error) {
120
+ if (isNotFound(error))
121
+ return missing;
122
+ return { status: 'unknown', detail: error instanceof Error ? error.message : String(error) };
123
+ }
124
+ }
@@ -6,7 +6,10 @@
6
6
  // 2. 만들어 둔 버전의 releaseType 을 나중에 바꾸기 (PATCH appStoreVersions)
7
7
  // 3. 단계적 출시 시작·일시중지·재개·즉시완료 (phasedRelease)
8
8
  // Play 는 userFraction/halted 로 3번이 되는데 iOS 만 비어 있었다.
9
+ import { z } from 'zod';
10
+ import { apiPatch, apiPost } from './client.js';
9
11
  import { V1_BASE, apiRequest, authHeadersOrThrow, isNotFound } from './http.js';
12
+ import { appStoreResourceRef, appStoreToOne, getAppStoreResponse, includedAppStoreResource } from './read-response.js';
10
13
  import { encodePathSegment } from '../lib/url-path.js';
11
14
  /** 각 상태가 "지금 출시" 요청을 받을 수 있는지 + 사람이 읽을 설명. */
12
15
  const STATE_NOTE = {
@@ -20,48 +23,79 @@ const STATE_NOTE = {
20
23
  REJECTED: 'Apple 이 거절함 — 수정 후 재제출.',
21
24
  METADATA_REJECTED: '메타데이터 거절 — 수정 후 재제출.',
22
25
  };
23
- async function get(path, params) {
24
- const headers = await authHeadersOrThrow();
25
- const query = params ? `?${new URLSearchParams(params).toString()}` : '';
26
- return apiRequest(V1_BASE, `${path}${query}`, headers, { method: 'GET' });
27
- }
28
- async function send(method, path, body) {
29
- const headers = await authHeadersOrThrow();
30
- return apiRequest(V1_BASE, path, headers, {
31
- method,
32
- ...(body === undefined
33
- ? {}
34
- : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }),
26
+ const phasedType = 'appStoreVersionPhasedReleases';
27
+ const phasedRelation = 'appStoreVersionPhasedRelease';
28
+ const phasedFields = 'phasedReleaseState,startDate,totalPauseDuration,currentDayNumber';
29
+ const phasedRef = appStoreResourceRef.extend({
30
+ type: z.literal(phasedType),
31
+ });
32
+ const phasedResource = phasedRef.extend({
33
+ attributes: z.object({
34
+ phasedReleaseState: z.enum(['INACTIVE', 'ACTIVE', 'PAUSED', 'COMPLETE']),
35
+ currentDayNumber: z.number().nullish(),
36
+ startDate: z.string().nullish(),
37
+ totalPauseDuration: z.number().nullish(),
38
+ }),
39
+ });
40
+ const phasedResponse = z.object({ data: phasedResource.nullable() });
41
+ const phasedCreateResponse = z.object({ data: phasedRef });
42
+ const releaseDocument = z.object({
43
+ data: appStoreResourceRef.extend({
44
+ type: z.literal('appStoreVersions'),
45
+ attributes: z.object({
46
+ versionString: z.string().nullish(),
47
+ appStoreState: z.string().nullish(),
48
+ appVersionState: z.string().nullish(),
49
+ releaseType: z.string().nullish(),
50
+ earliestReleaseDate: z.string().nullish(),
51
+ }).nullish(),
52
+ relationships: z.object({ [phasedRelation]: z.unknown().optional() }).nullish(),
53
+ }),
54
+ included: z.array(z.unknown()).nullish(),
55
+ });
56
+ async function readVersion(versionId, includePhased = false) {
57
+ const fields = 'versionString,appStoreState,appVersionState,releaseType,earliestReleaseDate';
58
+ const document = await getAppStoreResponse(releaseDocument, `/appStoreVersions/${encodePathSegment(versionId)}`, {
59
+ 'fields[appStoreVersions]': includePhased ? `${fields},${phasedRelation}` : fields,
60
+ ...(includePhased ? { include: phasedRelation, [`fields[${phasedType}]`]: phasedFields } : {}),
35
61
  });
62
+ if (document.data.id !== versionId)
63
+ throw new Error('App Store Connect에서 요청한 버전과 다른 버전을 반환했습니다.');
64
+ return document;
65
+ }
66
+ function versionSummary(row) {
67
+ const a = row.attributes;
68
+ return {
69
+ versionId: row.id,
70
+ versionString: a?.versionString ?? undefined,
71
+ state: a?.appStoreState ?? a?.appVersionState ?? undefined,
72
+ releaseType: a?.releaseType ?? undefined,
73
+ earliestReleaseDate: a?.earliestReleaseDate ?? undefined,
74
+ };
36
75
  }
37
76
  export async function getVersionSummary(versionId) {
38
- const data = await get(`/appStoreVersions/${encodePathSegment(versionId)}`, { 'fields[appStoreVersions]': 'versionString,appStoreState,releaseType,earliestReleaseDate' });
39
- const a = data.data?.attributes ?? {};
77
+ return versionSummary((await readVersion(versionId)).data);
78
+ }
79
+ function phasedSummary(row) {
80
+ const attributes = row.attributes;
40
81
  return {
41
- versionId,
42
- versionString: a.versionString,
43
- state: a.appStoreState,
44
- releaseType: a.releaseType,
45
- earliestReleaseDate: a.earliestReleaseDate,
82
+ id: row.id,
83
+ state: attributes.phasedReleaseState,
84
+ currentDayNumber: attributes.currentDayNumber ?? undefined,
85
+ startDate: attributes.startDate ?? undefined,
86
+ totalPauseDuration: attributes.totalPauseDuration ?? undefined,
46
87
  };
47
88
  }
48
89
  /** to-one 관계는 없을 때 200 + data:null 로 오기도 하고 404 로 오기도 한다. 둘 다 "없음"으로 본다. */
49
- async function getPhasedRelease(versionId) {
90
+ async function getPhasedRelease(versionId, linkedId) {
50
91
  try {
51
- const data = await get(`/appStoreVersions/${encodePathSegment(versionId)}/appStoreVersionPhasedRelease`);
52
- if (!data.data)
53
- return null;
54
- const a = (data.data.attributes ?? {});
55
- return {
56
- id: data.data.id,
57
- state: a.phasedReleaseState,
58
- currentDayNumber: a.currentDayNumber,
59
- startDate: a.startDate,
60
- totalPauseDuration: a.totalPauseDuration,
61
- };
92
+ const { data } = await getAppStoreResponse(phasedResponse, `/appStoreVersions/${encodePathSegment(versionId)}/appStoreVersionPhasedRelease`, { [`fields[${phasedType}]`]: phasedFields });
93
+ if (linkedId && data?.id !== linkedId)
94
+ throw new Error('App Store Connect의 단계적 출시 연결과 상세 조회 결과가 일치하지 않습니다.');
95
+ return data ? phasedSummary(data) : null;
62
96
  }
63
97
  catch (err) {
64
- if (isNotFound(err))
98
+ if (!linkedId && isNotFound(err))
65
99
  return null;
66
100
  throw err;
67
101
  }
@@ -71,8 +105,12 @@ export function stateNote(state) {
71
105
  }
72
106
  /** 버전 상태 + 단계적 출시 상태를 한 번에. 쓰기 전 미리보기용. */
73
107
  export async function getReleaseStatus(versionId) {
74
- const version = await getVersionSummary(versionId);
75
- const phased = await getPhasedRelease(versionId);
108
+ const document = await readVersion(versionId, true);
109
+ const version = versionSummary(document.data);
110
+ const linkage = appStoreToOne.safeParse(document.data.relationships?.[phasedRelation]).data?.data;
111
+ const ref = linkage?.type === phasedType ? linkage : undefined;
112
+ const included = ref && includedAppStoreResource(document.included, ref, phasedResource);
113
+ const phased = linkage === null ? null : included ? phasedSummary(included) : await getPhasedRelease(versionId, ref?.id);
76
114
  return { version, phased, note: stateNote(version.state) };
77
115
  }
78
116
  /**
@@ -91,7 +129,7 @@ export async function requestRelease(versionId) {
91
129
  .filter(Boolean)
92
130
  .join('\n'));
93
131
  }
94
- await send('POST', '/appStoreVersionReleaseRequests', {
132
+ await apiPost('/appStoreVersionReleaseRequests', {
95
133
  data: {
96
134
  type: 'appStoreVersionReleaseRequests',
97
135
  relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: versionId } } },
@@ -115,7 +153,7 @@ export async function updateReleaseType(args) {
115
153
  attributes.earliestReleaseDate = earliestReleaseDate;
116
154
  else if (earliestReleaseDate === undefined)
117
155
  attributes.earliestReleaseDate = null;
118
- await send('PATCH', `/appStoreVersions/${encodePathSegment(versionId)}`, {
156
+ await apiPatch(`/appStoreVersions/${encodePathSegment(versionId)}`, {
119
157
  data: { type: 'appStoreVersions', id: versionId, attributes },
120
158
  });
121
159
  return getVersionSummary(versionId);
@@ -131,23 +169,23 @@ export async function updateReleaseType(args) {
131
169
  */
132
170
  export async function setPhasedRelease(args) {
133
171
  const { versionId, action } = args;
134
- const version = await getVersionSummary(versionId);
135
- const current = await getPhasedRelease(versionId);
172
+ const { version, phased: current } = await getReleaseStatus(versionId);
136
173
  if (action === 'enable') {
137
174
  if (!current) {
138
- const created = await send('POST', '/appStoreVersionPhasedReleases', {
175
+ const result = await apiPost('/appStoreVersionPhasedReleases', {
139
176
  data: {
140
177
  type: 'appStoreVersionPhasedReleases',
141
178
  attributes: { phasedReleaseState: 'ACTIVE' },
142
179
  relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: versionId } } },
143
180
  },
144
181
  });
145
- void created;
146
- }
147
- else if (current.state === 'PAUSED') {
148
- await patchState(current.id, 'ACTIVE');
182
+ const createdId = phasedCreateResponse.safeParse(result).data?.data.id;
183
+ return { action, phased: await verifyPhasedChange(versionId, createdId), version };
149
184
  }
150
- return { action, phased: await getPhasedRelease(versionId), version };
185
+ if (current.state !== 'PAUSED')
186
+ return { action, phased: current, version };
187
+ await patchState(current.id, 'ACTIVE');
188
+ return { action, phased: await verifyPhasedChange(versionId, current.id, 'ACTIVE'), version };
151
189
  }
152
190
  if (!current) {
153
191
  throw new Error([
@@ -156,15 +194,30 @@ export async function setPhasedRelease(args) {
156
194
  ].join('\n'));
157
195
  }
158
196
  if (action === 'disable') {
159
- await send('DELETE', `/appStoreVersionPhasedReleases/${encodePathSegment(current.id)}`);
197
+ await apiRequest(V1_BASE, `/appStoreVersionPhasedReleases/${encodePathSegment(current.id)}`, await authHeadersOrThrow(), {
198
+ method: 'DELETE',
199
+ });
160
200
  return { action, phased: null, version };
161
201
  }
162
202
  const next = action === 'pause' ? 'PAUSED' : action === 'resume' ? 'ACTIVE' : 'COMPLETE';
163
203
  await patchState(current.id, next);
164
- return { action, phased: await getPhasedRelease(versionId), version };
204
+ return { action, phased: await verifyPhasedChange(versionId, current.id, next), version };
205
+ }
206
+ async function verifyPhasedChange(versionId, id, expectedState) {
207
+ try {
208
+ const phased = await getPhasedRelease(versionId, id);
209
+ if (!phased || (expectedState && phased.state !== expectedState)) {
210
+ throw new Error('단계적 출시의 변경된 상태가 응답에 없습니다.');
211
+ }
212
+ return phased;
213
+ }
214
+ catch (error) {
215
+ const reason = error instanceof Error ? error.message : String(error);
216
+ throw new Error(`단계적 출시 변경 요청이 접수됐지만 결과를 확인할 수 없습니다. 상태를 먼저 조회하세요. 원인: ${reason}`, { cause: error });
217
+ }
165
218
  }
166
219
  async function patchState(phasedReleaseId, state) {
167
- await send('PATCH', `/appStoreVersionPhasedReleases/${encodePathSegment(phasedReleaseId)}`, {
220
+ await apiPatch(`/appStoreVersionPhasedReleases/${encodePathSegment(phasedReleaseId)}`, {
168
221
  data: {
169
222
  type: 'appStoreVersionPhasedReleases',
170
223
  id: phasedReleaseId,
@@ -0,0 +1,19 @@
1
+ /** Read the review target and preview together. Resolve missing included resources against that same version. */
2
+ export declare function buildSubmitForReviewPreview(versionId: string): Promise<{
3
+ versionId: string;
4
+ appId: string;
5
+ platform: string;
6
+ versionString: string;
7
+ state: string;
8
+ attachedBuild: {
9
+ id: string;
10
+ buildNumber: string;
11
+ uploadedDate: string | undefined;
12
+ processingState: string;
13
+ } | undefined;
14
+ whatsNewByLocale: {
15
+ locale: string;
16
+ length: number;
17
+ excerpt: string;
18
+ }[];
19
+ }>;
@@ -0,0 +1,141 @@
1
+ import { z } from 'zod';
2
+ import { collectPages } from '../lib/paginate.js';
3
+ import { encodePathSegment } from '../lib/url-path.js';
4
+ import { isNotFound } from './http.js';
5
+ import { appStoreNextPagePath, appStorePagination, appStoreResourceRef, appStoreToOne, getAppStoreResponse, includedAppStoreResource, pageIsIncomplete } from './read-response.js';
6
+ import { requireVersionAppAndPlatform } from './versions.js';
7
+ const buildFields = 'version,uploadedDate,processingState';
8
+ const localizationFields = 'locale,whatsNew';
9
+ const localizationType = 'appStoreVersionLocalizations';
10
+ const includedLocalizationLimit = 50;
11
+ const previewVersion = z.object({
12
+ data: appStoreResourceRef.extend({
13
+ type: z.literal('appStoreVersions'),
14
+ attributes: z.object({
15
+ platform: z.string().nullish(),
16
+ versionString: z.string().nullish(),
17
+ appStoreState: z.string().nullish(),
18
+ appVersionState: z.string().nullish(),
19
+ }).optional(),
20
+ relationships: z.object({
21
+ app: appStoreToOne.optional(),
22
+ build: z.unknown().optional(),
23
+ [localizationType]: z.unknown().optional(),
24
+ }).optional(),
25
+ }),
26
+ included: z.array(z.unknown()).nullish(),
27
+ });
28
+ const previewBuild = appStoreResourceRef.extend({
29
+ type: z.literal('builds'),
30
+ attributes: z.object({
31
+ version: z.string().trim().min(1),
32
+ uploadedDate: z.string().nullish(),
33
+ processingState: z.string().trim().min(1),
34
+ }),
35
+ });
36
+ const previewBuildResponse = z.object({ data: previewBuild.nullable() });
37
+ const localizationResource = appStoreResourceRef.extend({
38
+ type: z.literal(localizationType),
39
+ attributes: z.object({ locale: z.string().min(1), whatsNew: z.string().nullish() }),
40
+ });
41
+ const localizationLinkage = appStorePagination.extend({ data: z.array(appStoreResourceRef) });
42
+ const localizationPage = appStorePagination.extend({ data: z.array(localizationResource) });
43
+ const incompleteLocalizations = 'App Store Connect에서 출시 노트의 전체 로케일을 확인할 수 없습니다.';
44
+ async function readPreviewBuild(path, document) {
45
+ const link = appStoreToOne.safeParse(document.data.relationships?.build).data?.data;
46
+ if (link === null)
47
+ return undefined;
48
+ const ref = link?.type === 'builds' ? link : undefined;
49
+ const embedded = ref && includedAppStoreResource(document.included, ref, previewBuild);
50
+ if (embedded)
51
+ return embedded;
52
+ try {
53
+ const { data } = await getAppStoreResponse(previewBuildResponse, `${path}/build`, { 'fields[builds]': buildFields });
54
+ if (ref && data?.id !== ref.id)
55
+ throw new Error('App Store Connect의 빌드 연결과 상세 조회 결과가 일치하지 않습니다.');
56
+ return data ?? undefined;
57
+ }
58
+ catch (error) {
59
+ if (!ref && isNotFound(error))
60
+ return undefined;
61
+ throw error;
62
+ }
63
+ }
64
+ async function readPreviewLocalizations(path, document) {
65
+ const link = localizationLinkage.safeParse(document.data.relationships?.[localizationType]).data;
66
+ const paging = link?.meta?.paging;
67
+ if (link && !pageIsIncomplete(link, link.data.length)
68
+ && (link.data.length < (paging?.limit ?? includedLocalizationLimit) || paging?.total === link.data.length)
69
+ && new Set(link.data.map(({ id }) => id)).size === link.data.length) {
70
+ const embedded = link.data.map((ref) => includedAppStoreResource(document.included, ref, localizationResource));
71
+ if (embedded.every((row) => row !== undefined)
72
+ && new Set(embedded.map(({ attributes }) => attributes.locale.toLowerCase())).size === embedded.length) {
73
+ return embedded;
74
+ }
75
+ }
76
+ const endpoint = `${path}/appStoreVersionLocalizations`;
77
+ const params = {
78
+ [`fields[${localizationType}]`]: localizationFields,
79
+ limit: '200',
80
+ };
81
+ const ids = new Set();
82
+ const locales = new Set();
83
+ let total = paging?.total ?? 0;
84
+ const rows = await collectPages(async (next) => {
85
+ const page = await getAppStoreResponse(localizationPage, next ?? endpoint, next ? undefined : params);
86
+ for (const { id, attributes } of page.data) {
87
+ const locale = attributes.locale.toLowerCase();
88
+ if (ids.has(id) || locales.has(locale))
89
+ throw new Error(incompleteLocalizations);
90
+ ids.add(id);
91
+ locales.add(locale);
92
+ }
93
+ total = Math.max(total, page.meta?.paging?.total ?? 0);
94
+ const nextLink = page.links?.next;
95
+ if (!nextLink && (pageIsIncomplete(page, ids.size) || total > ids.size))
96
+ throw new Error(incompleteLocalizations);
97
+ return { items: page.data, nextPageToken: nextLink ? appStoreNextPagePath(endpoint, nextLink) : undefined };
98
+ });
99
+ if (link?.data.some(({ id, type }) => type === localizationType && !ids.has(id))) {
100
+ throw new Error('App Store Connect의 로케일 연결과 상세 조회 결과가 일치하지 않습니다.');
101
+ }
102
+ return rows;
103
+ }
104
+ /** Read the review target and preview together. Resolve missing included resources against that same version. */
105
+ export async function buildSubmitForReviewPreview(versionId) {
106
+ const path = `/appStoreVersions/${encodePathSegment(versionId)}`;
107
+ const document = await getAppStoreResponse(previewVersion, path, {
108
+ 'fields[appStoreVersions]': `platform,app,versionString,appStoreState,appVersionState,build,${localizationType}`,
109
+ 'fields[apps]': 'bundleId',
110
+ 'fields[builds]': buildFields,
111
+ [`fields[${localizationType}]`]: localizationFields,
112
+ [`limit[${localizationType}]`]: String(includedLocalizationLimit),
113
+ include: `app,build,${localizationType}`,
114
+ });
115
+ const { appId, platform } = requireVersionAppAndPlatform(versionId, document.data);
116
+ const attributes = document.data.attributes;
117
+ const versionString = attributes?.versionString;
118
+ const state = attributes?.appStoreState ?? attributes?.appVersionState;
119
+ if (!versionString?.trim() || !state?.trim()) {
120
+ throw new Error('App Store Connect에서 심사 대상의 버전명과 상태를 확인할 수 없습니다.');
121
+ }
122
+ const [build, localizations] = await Promise.all([
123
+ readPreviewBuild(path, document),
124
+ readPreviewLocalizations(path, document),
125
+ ]);
126
+ const whatsNewByLocale = localizations.flatMap(({ attributes: { locale, whatsNew } }) => whatsNew ? [{
127
+ locale, length: whatsNew.length, excerpt: whatsNew.length > 200 ? `${whatsNew.slice(0, 200)}…` : whatsNew,
128
+ }] : []);
129
+ return {
130
+ versionId, appId, platform,
131
+ versionString,
132
+ state,
133
+ attachedBuild: build && {
134
+ id: build.id,
135
+ buildNumber: build.attributes.version,
136
+ uploadedDate: build.attributes.uploadedDate ?? undefined,
137
+ processingState: build.attributes.processingState,
138
+ },
139
+ whatsNewByLocale,
140
+ };
141
+ }