@yoonion/mimi-seed-mcp 0.23.1 → 0.23.2

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.
@@ -0,0 +1,282 @@
1
+ import path from 'node:path';
2
+ import { stat } from 'node:fs/promises';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { z } from 'zod';
5
+ import { apiGet, apiPatch, apiPost } from './client.js';
6
+ import { listPlacementGroup, readyAssetStates } from './asset-library.js';
7
+ import { appStorePagination, getAppStoreResponse, pageIsIncomplete } from './read-response.js';
8
+ import { uploadFileParts } from './upload-parts.js';
9
+ import { getVersionAppAndPlatform } from './versions.js';
10
+ import { encodePathSegment } from '../lib/url-path.js';
11
+ const category = 'APP_SCREENSHOTS_AND_PREVIEWS';
12
+ const resourceId = z.string().min(1);
13
+ const resourceRef = z.object({ type: z.string(), id: resourceId });
14
+ const localizationDocument = z.object({
15
+ data: resourceRef.extend({
16
+ relationships: z.object({
17
+ appStoreVersion: z.object({ data: resourceRef.extend({ type: z.literal('appStoreVersions') }) }),
18
+ }),
19
+ }),
20
+ });
21
+ const idDocument = z.object({ data: resourceRef });
22
+ const responseAttributes = z.object({ state: z.string().nullish(), specId: z.string().nullish() });
23
+ const stateRecord = resourceRef.extend({ attributes: responseAttributes.nullish() });
24
+ const stateDocument = z.object({ data: stateRecord });
25
+ const statePage = appStorePagination.extend({ data: z.array(stateRecord) });
26
+ const uploadPlan = z.array(z.object({
27
+ method: z.literal('PUT'),
28
+ url: z.url({ protocol: /^https$/ }),
29
+ length: z.number().int().positive(),
30
+ offset: z.number().int().nonnegative(),
31
+ requestHeaders: z.array(z.object({ name: z.string(), value: z.string() })).default([]),
32
+ })).min(1);
33
+ const reservationDocument = z.object({
34
+ data: resourceRef.extend({ attributes: z.object({ uploadOperations: z.unknown() }).nullish() }),
35
+ });
36
+ const fileSpec = z.object({
37
+ specId: resourceId,
38
+ fileExtensions: z.array(z.string()),
39
+ maxFileSize: z.number().positive(),
40
+ });
41
+ const referenceData = z.object({ data: z.array(z.object({
42
+ attributes: z.object({
43
+ placementTypes: z.array(z.object({
44
+ placementTypeId: z.string(),
45
+ specMappings: z.array(z.object({ placementGroupId: z.string(), specs: z.array(resourceId) })).nullish(),
46
+ })),
47
+ imageSpecs: z.array(fileSpec).optional(),
48
+ videoSpecs: z.array(fileSpec).optional(),
49
+ }),
50
+ })) });
51
+ const assetTypes = {
52
+ APP_SCREENSHOT: { resource: 'appAssetLibraryImages', relation: 'image', specs: 'imageSpecs', collection: 'images' },
53
+ APP_PREVIEW: { resource: 'appAssetLibraryVideos', relation: 'video', specs: 'videoSpecs', collection: 'videos' },
54
+ };
55
+ function checked(schema, received, label) {
56
+ const parsed = schema.safeParse(received);
57
+ if (!parsed.success)
58
+ throw new Error(`App Store Connect ${label} 응답 형식이 올바르지 않습니다.`);
59
+ return parsed.data;
60
+ }
61
+ function link(type, id) {
62
+ return { data: { type, id } };
63
+ }
64
+ async function supportsPlacement(placementGroup, placementType) {
65
+ const specKey = assetTypes[placementType].specs;
66
+ const document = checked(referenceData, await apiGet('/appAssetLibraryRefData', {
67
+ 'filter[features]': 'APP_STORE_VERSIONS',
68
+ 'fields[appAssetLibraryRefData]': `placementTypes,${specKey}`,
69
+ }), '미디어 규격');
70
+ const records = document.data.map(({ attributes }) => attributes);
71
+ const mappings = records
72
+ .flatMap(({ placementTypes }) => placementTypes)
73
+ .filter(({ placementTypeId }) => placementTypeId === placementType)
74
+ .flatMap(({ specMappings }) => specMappings ?? []);
75
+ const supported = new Set(mappings.filter((mapping) => mapping.placementGroupId === placementGroup)
76
+ .flatMap(({ specs }) => specs));
77
+ const specs = records.flatMap((record) => record[specKey] ?? []).filter(({ specId }) => supported.has(specId));
78
+ if (specs.length === 0) {
79
+ const groups = [...new Set(mappings.map(({ placementGroupId }) => placementGroupId))];
80
+ throw new Error(`Apple ${placementType} 배치 그룹을 확인하세요. 지원 그룹: ${groups.join(', ') || '조회되지 않음'}`);
81
+ }
82
+ return specs;
83
+ }
84
+ async function libraryForLocalization(localizationId) {
85
+ const localization = checked(localizationDocument, await apiGet(`/appStoreVersionLocalizations/${encodePathSegment(localizationId)}`, {
86
+ include: 'appStoreVersion',
87
+ 'fields[appStoreVersionLocalizations]': 'appStoreVersion',
88
+ 'fields[appStoreVersions]': 'app',
89
+ }), '버전 로케일').data;
90
+ if (localization.id !== localizationId || localization.type !== 'appStoreVersionLocalizations') {
91
+ throw new Error('App Store Connect 응답의 버전 로케일이 요청과 일치하지 않습니다.');
92
+ }
93
+ const { appId } = await getVersionAppAndPlatform(localization.relationships.appStoreVersion.data.id);
94
+ const library = checked(idDocument, await apiGet(`/apps/${encodePathSegment(appId)}/assetLibrary`), 'Asset Library').data;
95
+ if (library.type !== 'appAssetLibraries')
96
+ throw new Error('App Store Connect의 Asset Library ID를 확인할 수 없습니다.');
97
+ return library.id;
98
+ }
99
+ function checkUploadPlan(value, fileSize) {
100
+ const operations = checked(uploadPlan, value, '업로드 조각');
101
+ let offset = 0;
102
+ for (const operation of [...operations].sort((a, b) => a.offset - b.offset)) {
103
+ const url = new URL(operation.url);
104
+ if (url.username || url.password || operation.offset !== offset || operation.length > fileSize - offset) {
105
+ throw new Error('Apple 업로드 조각이 요청 파일의 바이트 범위와 일치하지 않습니다.');
106
+ }
107
+ offset += operation.length;
108
+ }
109
+ if (offset !== fileSize)
110
+ throw new Error('Apple 업로드 조각이 요청 파일 전체를 포함하지 않습니다.');
111
+ return operations;
112
+ }
113
+ async function readAssetState(resource, assetId) {
114
+ const response = await getAppStoreResponse(stateDocument, `/${encodePathSegment(resource)}/${encodePathSegment(assetId)}`, {
115
+ [`fields[${resource}]`]: 'state,specId',
116
+ });
117
+ if (response.data.id !== assetId || response.data.type !== resource) {
118
+ throw new Error('대상 에셋 유형 또는 ID가 일치하지 않습니다.');
119
+ }
120
+ return response.data.attributes;
121
+ }
122
+ async function readLibraryAsset(localizationId, placementType, assetId) {
123
+ const libraryId = await libraryForLocalization(localizationId);
124
+ const { resource, collection } = assetTypes[placementType];
125
+ const page = await getAppStoreResponse(statePage, `/appAssetLibraries/${encodePathSegment(libraryId)}/${encodePathSegment(collection)}`, { 'filter[id]': assetId, [`fields[${resource}]`]: 'state,specId', limit: '1' });
126
+ const [asset] = page.data;
127
+ if (pageIsIncomplete(page, page.data.length) || page.data.length !== 1 || asset.id !== assetId || asset.type !== resource) {
128
+ throw new Error('대상 앱의 Asset Library에서 해당 에셋을 확인할 수 없습니다.');
129
+ }
130
+ return asset.attributes;
131
+ }
132
+ export async function uploadAndPlaceMedia(args) {
133
+ const { localizationId, placementGroup, placementType, filePath, previewFrameTimeCode } = args;
134
+ if (Boolean(filePath) === Boolean(args.assetId))
135
+ throw new Error('filePath 또는 assetId 중 하나를 지정하세요.');
136
+ if (previewFrameTimeCode && (!filePath || placementType !== 'APP_PREVIEW')) {
137
+ throw new Error('previewFrameTimeCode는 미리보기 파일 업로드에만 적용됩니다.');
138
+ }
139
+ if (filePath && !path.isAbsolute(filePath))
140
+ throw new Error('filePath는 로컬 파일의 절대 경로여야 합니다.');
141
+ const file = filePath ? await stat(filePath) : undefined;
142
+ if (file && (!file.isFile() || file.size <= 0))
143
+ throw new Error('내용이 있는 일반 미디어 파일을 지정하세요.');
144
+ const { resource, relation } = assetTypes[placementType];
145
+ const specs = await supportsPlacement(placementGroup, placementType);
146
+ let assetId = args.assetId;
147
+ let asset;
148
+ let stage = 'placement';
149
+ try {
150
+ if (filePath && file) {
151
+ const fileName = path.basename(filePath);
152
+ const extension = path.extname(fileName).toLowerCase();
153
+ if (!specs.some((spec) => spec.fileExtensions.includes(extension) && file.size <= spec.maxFileSize)) {
154
+ throw new Error('이 배치 그룹의 Apple 미디어 규격에 맞는 파일 확장자와 크기를 확인하세요.');
155
+ }
156
+ const libraryId = await libraryForLocalization(localizationId);
157
+ const reserved = checked(reservationDocument, await apiPost(`/${encodePathSegment(resource)}`, {
158
+ data: {
159
+ type: resource,
160
+ attributes: { category, fileName, fileSize: file.size, ...(previewFrameTimeCode ? { previewFrameTimeCode } : {}) },
161
+ relationships: { assetLibrary: link('appAssetLibraries', libraryId) },
162
+ },
163
+ }), '미디어 예약').data;
164
+ if (reserved.type !== resource)
165
+ throw new Error('예약된 에셋 유형을 확인할 수 없습니다.');
166
+ assetId = reserved.id;
167
+ stage = 'upload';
168
+ const operations = checkUploadPlan(reserved.attributes?.uploadOperations, file.size);
169
+ await uploadFileParts(filePath, operations, 'error');
170
+ const afterUpload = await stat(filePath);
171
+ if (afterUpload.size !== file.size || afterUpload.mtimeMs !== file.mtimeMs || afterUpload.ino !== file.ino) {
172
+ throw new Error('업로드 중 로컬 파일이 변경되어 완료 요청을 중단했습니다.');
173
+ }
174
+ stage = 'commit';
175
+ const commit = checked(stateDocument, await apiPatch(`/${encodePathSegment(resource)}/${encodePathSegment(assetId)}`, {
176
+ data: { type: resource, id: assetId, attributes: { uploaded: true } },
177
+ }), '미디어 업로드 완료').data;
178
+ if (commit.id !== assetId || commit.type !== resource)
179
+ throw new Error('업로드 완료 응답의 에셋 ID를 확인할 수 없습니다.');
180
+ asset = commit.attributes;
181
+ stage = 'placement';
182
+ for (const waitMs of [0, 2_000, 4_000]) {
183
+ if (asset?.state && asset.state !== 'UPLOAD_COMPLETE' && (!readyAssetStates.has(asset.state) || asset.specId))
184
+ break;
185
+ if (waitMs)
186
+ await delay(waitMs);
187
+ asset = await readAssetState(resource, assetId);
188
+ }
189
+ }
190
+ else if (assetId) {
191
+ const related = (await listPlacementGroup(localizationId, placementGroup, relation))
192
+ .filter((row) => row.placementType === placementType);
193
+ const existing = related.filter((row) => row.assetId === assetId);
194
+ if (existing.length === 1) {
195
+ return { status: 'placed', assetId, placementGroup, placementId: existing[0].placementId, placementState: existing[0].placementState, assetState: existing[0].assetState, reusedPlacement: true };
196
+ }
197
+ if (existing.length > 1 || related.some((row) => !row.assetId)) {
198
+ throw new Error('대상 그룹의 기존 미디어 배치를 하나로 확인할 수 없습니다. 배치 목록을 확인하세요.');
199
+ }
200
+ asset = await readLibraryAsset(localizationId, placementType, assetId);
201
+ }
202
+ if (!assetId)
203
+ throw new Error('App Store Connect 에셋 ID를 확인할 수 없습니다.');
204
+ const assetState = asset?.state ?? undefined;
205
+ if (assetState === 'UPLOAD_COMPLETE') {
206
+ return {
207
+ status: 'processing', assetId, assetState, placementGroup,
208
+ message: 'Apple에서 에셋을 처리 중입니다. 처리 완료 후 같은 assetId로 배치를 다시 요청하세요.',
209
+ };
210
+ }
211
+ if (!assetState || !readyAssetStates.has(assetState)) {
212
+ throw new Error(`배치할 수 있는 에셋 상태를 확인할 수 없습니다 (${assetState ?? '상태 미상'}).`);
213
+ }
214
+ const assetSpecId = asset?.specId;
215
+ if (!assetSpecId || !specs.some(({ specId }) => specId === assetSpecId)) {
216
+ throw new Error('처리된 에셋이 대상 배치 그룹의 규격에 맞는지 확인할 수 없습니다.');
217
+ }
218
+ const placement = checked(stateDocument, await apiPost('/appAssetLibraryPlacements', {
219
+ data: {
220
+ type: 'appAssetLibraryPlacements',
221
+ attributes: { placementType, placementGroup },
222
+ relationships: {
223
+ [relation]: link(resource, assetId),
224
+ appStoreVersionLocalization: link('appStoreVersionLocalizations', localizationId),
225
+ },
226
+ },
227
+ }), '미디어 배치').data;
228
+ if (placement.type !== 'appAssetLibraryPlacements')
229
+ throw new Error('App Store Connect의 배치 ID를 확인할 수 없습니다.');
230
+ return {
231
+ status: 'placed', assetId, placementGroup, placementId: placement.id, assetState,
232
+ placementState: placement.attributes?.state ?? undefined, reusedPlacement: false,
233
+ };
234
+ }
235
+ catch (error) {
236
+ if (!assetId)
237
+ throw error;
238
+ const detail = error instanceof Error ? error.message : String(error);
239
+ const recovery = stage === 'upload'
240
+ ? '파일 전송을 완료하지 못했습니다. 남은 예약을 확인한 뒤 파일 업로드를 다시 시작하세요.'
241
+ : stage === 'commit'
242
+ ? '업로드 완료 요청의 결과를 확인하세요. 처리가 시작됐다면 기존 assetId로 이어갈 수 있습니다.'
243
+ : '에셋 상태와 대상 그룹의 현재 배치를 확인하세요.';
244
+ throw new Error(`Asset Library 에셋 ${assetId}: ${detail} ${recovery}`, { cause: error });
245
+ }
246
+ }
247
+ function sameOrder(current, requested) {
248
+ return current.length === requested.length && current.every((id, index) => id === requested[index]);
249
+ }
250
+ export async function reorderMediaPlacements(args) {
251
+ const { localizationId, placementGroup, placementIds } = args;
252
+ const requested = new Set(placementIds);
253
+ if (requested.size === 0 || requested.size !== placementIds.length)
254
+ throw new Error('중복 없는 배치 ID를 순서대로 지정하세요.');
255
+ const readOrder = async () => (await listPlacementGroup(localizationId, placementGroup)).map(({ placementId }) => placementId);
256
+ const current = await readOrder();
257
+ if (current.length !== placementIds.length || new Set(current).size !== current.length
258
+ || current.some((id) => !requested.has(id))) {
259
+ throw new Error('대상 로케일과 배치 그룹의 기존 배치 ID 전체를 한 번씩 지정하세요.');
260
+ }
261
+ if (sameOrder(current, placementIds))
262
+ return { changed: false, placementGroup, placementIds: current };
263
+ const request = checked(idDocument, await apiPost('/appAssetLibraryPlacementOrderingRequests', {
264
+ data: {
265
+ type: 'appAssetLibraryPlacementOrderingRequests',
266
+ attributes: { placementGroup },
267
+ relationships: {
268
+ orderedPlacements: { data: placementIds.map((id) => ({ type: 'appAssetLibraryPlacements', id })) },
269
+ appStoreVersionLocalization: link('appStoreVersionLocalizations', localizationId),
270
+ },
271
+ },
272
+ }), '배치 순서 변경').data;
273
+ if (request.type !== 'appAssetLibraryPlacementOrderingRequests')
274
+ throw new Error('App Store Connect의 순서 변경 요청 ID를 확인할 수 없습니다.');
275
+ const verificationError = `배치 순서 변경 요청 ${request.id} 생성 후 실제 표시 순서를 확인할 수 없습니다. 목록을 다시 조회하세요.`;
276
+ const updated = await readOrder().catch((error) => {
277
+ throw new Error(verificationError, { cause: error });
278
+ });
279
+ if (!sameOrder(updated, placementIds))
280
+ throw new Error(verificationError);
281
+ return { changed: true, orderingRequestId: request.id, placementGroup, placementIds: updated };
282
+ }
@@ -0,0 +1,28 @@
1
+ type MediaKind = 'screenshots' | 'previews';
2
+ export type ScreenshotReadiness = 'ready' | 'missing' | 'not-ready' | 'unknown';
3
+ export interface MediaPlacement {
4
+ placementId: string;
5
+ placementType: string;
6
+ placementGroup?: string;
7
+ placementState?: string;
8
+ assetId?: string;
9
+ assetState?: string;
10
+ fileName?: string;
11
+ fileSize?: number;
12
+ previewFrameTimeCode?: string;
13
+ }
14
+ export declare const readyAssetStates: ReadonlySet<string>;
15
+ /** A recognized ready placement proves presence even if the provider has more placements. */
16
+ export declare function screenshotPlacementReadiness(rows: readonly MediaPlacement[], complete?: boolean): ScreenshotReadiness;
17
+ export declare function indexIncludedPlacements(included: readonly unknown[]): ReadonlyMap<string, MediaPlacement>;
18
+ /** Use the version localization's own linkage to attribute included placements. */
19
+ export declare function includedScreenshotReadiness(linkage: unknown, included: ReadonlyMap<string, MediaPlacement>): ScreenshotReadiness;
20
+ /** Reads a single localization, including the referenced asset metadata. */
21
+ export declare function listMediaPlacements(localizationId: string, kind: MediaKind): Promise<MediaPlacement[] | null>;
22
+ export declare function listPlacementGroup(localizationId: string, placementGroup: string, includeAsset?: 'image' | 'video'): Promise<MediaPlacement[]>;
23
+ /** Preserve the existing listing for set-based media during the provider migration. */
24
+ export declare function listProductPageMedia<T>(localizationId: string, kind: MediaKind, listLegacySets: (localizationId: string) => Promise<T[]>): Promise<{
25
+ placements: MediaPlacement[];
26
+ legacySets: T[];
27
+ }>;
28
+ export {};
@@ -0,0 +1,204 @@
1
+ import { z } from 'zod';
2
+ import { apiGet } from './client.js';
3
+ import { isNotFound, V1_BASE } from './http.js';
4
+ import { collectPages } from '../lib/paginate.js';
5
+ import { encodePathSegment } from '../lib/url-path.js';
6
+ const id = z.string().min(1);
7
+ const resourceRef = z.object({ type: z.string(), id });
8
+ const relationship = z.object({ data: resourceRef.nullish() }).nullish();
9
+ const paging = {
10
+ links: z.object({ next: z.string().nullish() }).nullish(),
11
+ meta: z.object({ paging: z.object({
12
+ total: z.number().int().nonnegative().optional(),
13
+ nextCursor: z.string().nullish(),
14
+ }).optional() }).nullish(),
15
+ };
16
+ const placementRecord = z.object({
17
+ type: z.literal('appAssetLibraryPlacements'),
18
+ id,
19
+ attributes: z.object({
20
+ placementType: z.string().min(1),
21
+ placementGroup: z.string().nullish(),
22
+ state: z.string().nullish(),
23
+ }),
24
+ relationships: z.object({ image: relationship, video: relationship }).nullish(),
25
+ });
26
+ const includedResource = resourceRef.extend({
27
+ attributes: z.object({
28
+ fileName: z.string().nullish(),
29
+ fileSize: z.number().nullish(),
30
+ state: z.string().nullish(),
31
+ previewFrameTimeCode: z.string().nullish(),
32
+ }).nullish(),
33
+ });
34
+ const placementPage = z.object({
35
+ ...paging,
36
+ data: z.array(placementRecord),
37
+ included: z.array(z.unknown()).nullish(),
38
+ });
39
+ const placementLinkage = z.object({ ...paging, data: z.array(resourceRef) });
40
+ const screenshotTypes = ['APP_SCREENSHOT', 'IMESSAGE_APP_SCREENSHOT'];
41
+ const readyPlacementStates = new Set([
42
+ 'ACTIVE', 'PARENT_PREPARE_FOR_SUBMISSION', 'PARENT_READY_FOR_REVIEW', 'PARENT_WAITING_FOR_REVIEW',
43
+ 'PARENT_IN_REVIEW', 'PARENT_APPROVED',
44
+ ]);
45
+ export const readyAssetStates = new Set([
46
+ 'PREPARE_FOR_SUBMISSION', 'READY_FOR_REVIEW', 'WAITING_FOR_REVIEW', 'IN_REVIEW', 'ACCEPTED', 'APPROVED',
47
+ ]);
48
+ const blockedAssetStates = new Set(['AWAITING_UPLOAD', 'UPLOAD_COMPLETE', 'FAILED', 'REJECTED', 'ARCHIVED']);
49
+ function toPlacement(row, assets) {
50
+ const video = row.attributes.placementType === 'APP_PREVIEW';
51
+ const ref = video ? row.relationships?.video?.data : row.relationships?.image?.data;
52
+ const assetId = ref?.type === (video ? 'appAssetLibraryVideos' : 'appAssetLibraryImages') ? ref.id : undefined;
53
+ const included = ref && assetId ? includedResource.safeParse(assets?.get(`${ref.type}:${assetId}`)) : undefined;
54
+ const asset = included?.success ? included.data.attributes : undefined;
55
+ return {
56
+ placementId: row.id,
57
+ placementType: row.attributes.placementType,
58
+ placementGroup: row.attributes.placementGroup ?? undefined,
59
+ placementState: row.attributes.state ?? undefined,
60
+ assetId,
61
+ assetState: asset?.state ?? undefined,
62
+ fileName: asset?.fileName ?? undefined,
63
+ fileSize: asset?.fileSize ?? undefined,
64
+ previewFrameTimeCode: asset?.previewFrameTimeCode ?? undefined,
65
+ };
66
+ }
67
+ /** A recognized ready placement proves presence even if the provider has more placements. */
68
+ export function screenshotPlacementReadiness(rows, complete = true) {
69
+ let hasScreenshot = false;
70
+ let unknown = !complete;
71
+ for (const row of rows) {
72
+ if (row.placementType !== 'APP_SCREENSHOT')
73
+ continue;
74
+ hasScreenshot = true;
75
+ if (row.placementState === 'ASSET_PROCESSING' || row.placementState === 'FAILED')
76
+ continue;
77
+ if (!row.placementState || !readyPlacementStates.has(row.placementState) || !row.assetId) {
78
+ unknown = true;
79
+ continue;
80
+ }
81
+ if (row.assetState && readyAssetStates.has(row.assetState))
82
+ return 'ready';
83
+ if (!row.assetState || !blockedAssetStates.has(row.assetState))
84
+ unknown = true;
85
+ }
86
+ return unknown ? 'unknown' : hasScreenshot ? 'not-ready' : 'missing';
87
+ }
88
+ function indexIncludedResources(included) {
89
+ const resources = new Map();
90
+ for (const item of included) {
91
+ const ref = resourceRef.safeParse(item);
92
+ if (ref.success) {
93
+ const key = `${ref.data.type}:${ref.data.id}`;
94
+ resources.set(key, resources.has(key) ? undefined : item);
95
+ }
96
+ }
97
+ return resources;
98
+ }
99
+ export function indexIncludedPlacements(included) {
100
+ const resources = indexIncludedResources(included);
101
+ const placements = new Map();
102
+ for (const item of resources.values()) {
103
+ const row = placementRecord.safeParse(item);
104
+ if (row.success)
105
+ placements.set(row.data.id, toPlacement(row.data, resources));
106
+ }
107
+ return placements;
108
+ }
109
+ /** Use the version localization's own linkage to attribute included placements. */
110
+ export function includedScreenshotReadiness(linkage, included) {
111
+ const parsed = placementLinkage.safeParse(linkage);
112
+ if (!parsed.success)
113
+ return 'unknown';
114
+ const { data, links, meta } = parsed.data;
115
+ const rows = data.flatMap((ref) => {
116
+ const placement = ref.type === 'appAssetLibraryPlacements' ? included.get(ref.id) : undefined;
117
+ return placement ? [placement] : [];
118
+ });
119
+ const complete = rows.length === data.length && !links?.next && !meta?.paging?.nextCursor
120
+ && (meta?.paging?.total ?? data.length) <= data.length;
121
+ return screenshotPlacementReadiness(rows, complete);
122
+ }
123
+ /** Reads a single localization, including the referenced asset metadata. */
124
+ export function listMediaPlacements(localizationId, kind) {
125
+ const types = kind === 'screenshots' ? screenshotTypes : ['APP_PREVIEW'];
126
+ const primary = kind === 'screenshots' ? 'image' : 'video';
127
+ const assetType = kind === 'screenshots' ? 'appAssetLibraryImages' : 'appAssetLibraryVideos';
128
+ return readPlacements(localizationId, {
129
+ 'filter[placementType]': types.join(','),
130
+ 'fields[appAssetLibraryPlacements]': `placementType,placementGroup,state,${primary}`,
131
+ [`fields[${assetType}]`]: `fileName,fileSize,state${kind === 'previews' ? ',previewFrameTimeCode' : ''}`,
132
+ include: primary,
133
+ }).then((rows) => rows?.filter((row) => types.includes(row.placementType)) ?? null);
134
+ }
135
+ export async function listPlacementGroup(localizationId, placementGroup, includeAsset) {
136
+ const assetType = includeAsset === 'video' ? 'appAssetLibraryVideos' : 'appAssetLibraryImages';
137
+ const rows = await readPlacements(localizationId, {
138
+ 'filter[placementGroup]': placementGroup,
139
+ 'fields[appAssetLibraryPlacements]': 'placementType,placementGroup,state,image,video',
140
+ ...(includeAsset ? { include: includeAsset, [`fields[${assetType}]`]: 'state' } : {}),
141
+ });
142
+ if (!rows || rows.some((row) => row.placementGroup !== placementGroup)) {
143
+ throw new Error('App Store Connect에서 대상 미디어 배치 그룹을 확인할 수 없습니다.');
144
+ }
145
+ return rows;
146
+ }
147
+ async function readPlacements(localizationId, filters) {
148
+ const path = `/appStoreVersionLocalizations/${encodePathSegment(localizationId)}/placements`;
149
+ const params = { limit: '200', sort: 'placementGroupPosition', ...filters };
150
+ let first;
151
+ try {
152
+ first = await apiGet(path, params);
153
+ }
154
+ catch (error) {
155
+ if (isNotFound(error))
156
+ return null;
157
+ throw error;
158
+ }
159
+ const base = new URL(V1_BASE);
160
+ const seen = new Set();
161
+ let total = 0;
162
+ return collectPages(async (next) => {
163
+ const page = placementPage.safeParse(next ? await apiGet(next) : first);
164
+ if (!page.success)
165
+ throw new Error('App Store Connect의 미디어 배치 응답 형식이 올바르지 않습니다.');
166
+ const { data, included, links, meta } = page.data;
167
+ const assets = indexIncludedResources(included ?? []);
168
+ for (const row of data) {
169
+ if (seen.has(row.id))
170
+ throw new Error('App Store Connect의 미디어 배치 ID가 중복됩니다.');
171
+ seen.add(row.id);
172
+ }
173
+ total = Math.max(total, meta?.paging?.total ?? 0);
174
+ let nextPageToken;
175
+ if (links?.next) {
176
+ const url = new URL(links.next, `${V1_BASE}${path}`);
177
+ if (url.origin !== base.origin || url.pathname !== `${base.pathname}${path}` || url.username || url.password) {
178
+ throw new Error('App Store Connect의 미디어 배치 페이지 링크가 올바르지 않습니다.');
179
+ }
180
+ nextPageToken = `${path}${url.search}`;
181
+ }
182
+ else if (meta?.paging?.nextCursor || total > seen.size) {
183
+ throw new Error('App Store Connect의 미디어 배치 목록이 불완전합니다.');
184
+ }
185
+ return {
186
+ items: data.map((row) => toPlacement(row, assets)),
187
+ nextPageToken,
188
+ };
189
+ });
190
+ }
191
+ /** Preserve the existing listing for set-based media during the provider migration. */
192
+ export async function listProductPageMedia(localizationId, kind, listLegacySets) {
193
+ const [placements, legacySets] = await Promise.all([
194
+ listMediaPlacements(localizationId, kind),
195
+ listLegacySets(localizationId).catch((error) => {
196
+ if (isNotFound(error))
197
+ return null;
198
+ throw error;
199
+ }),
200
+ ]);
201
+ if (!placements && !legacySets)
202
+ throw new Error('App Store Connect에서 대상 로컬라이제이션의 미디어를 찾을 수 없습니다.');
203
+ return { placements: placements ?? [], legacySets: legacySets ?? [] };
204
+ }
@@ -1,4 +1,5 @@
1
- export declare function apiGet(path: string, params?: Record<string, string>): Promise<any>;
1
+ import { type UntypedAscJson } from './http.js';
2
+ export declare function apiGet<T = UntypedAscJson>(path: string, params?: Record<string, string>): Promise<T>;
2
3
  export interface AppStoreVerifyResult {
3
4
  ok: boolean;
4
5
  stage: 'creds' | 'sign' | 'auth' | 'api' | 'done';
@@ -17,6 +18,6 @@ export interface AppStoreVerifyResult {
17
18
  * "첫 호출 401" 로 늦게 터지기 전에 setup 단계에서 잡아준다.
18
19
  */
19
20
  export declare function verifyAppStoreCredentials(creds?: import("./auth.js").AppStoreCredentials | null): Promise<AppStoreVerifyResult>;
20
- export declare function apiPatch(path: string, body: unknown): Promise<any>;
21
+ export declare function apiPatch<T = UntypedAscJson>(path: string, body: unknown): Promise<T>;
21
22
  /** 201 Created — 본문에 created entity. 일부 엔드포인트는 204 (→ { ok: true }). */
22
- export declare function apiPost(path: string, body: unknown): Promise<any>;
23
+ export declare function apiPost<T = UntypedAscJson>(path: string, body: unknown): Promise<T>;
@@ -6,6 +6,7 @@
6
6
  //
7
7
  // Play 쪽 대응물(데이터 안전 CSV)은 playstore/data-safety.ts 에 있다 — 자격증명 계통이 달라서 파일을 나눴다.
8
8
  import { V1_BASE, V2_BASE, apiRequest, authHeadersOrThrow, isNotFound } from './http.js';
9
+ import { requireAppInfo } from './app-info.js';
9
10
  import { encodePathSegment } from '../lib/url-path.js';
10
11
  async function get(base, path, params) {
11
12
  const headers = await authHeadersOrThrow();
@@ -20,20 +21,11 @@ async function send(base, method, path, body) {
20
21
  body: JSON.stringify(body),
21
22
  });
22
23
  }
23
- /** 연령 등급은 appInfo 에 딸려 있다. 편집 가능한 appInfo 를 우선 고른다. */
24
- async function resolveAppInfoId(appId) {
25
- const data = await get(V1_BASE, `/apps/${encodePathSegment(appId)}/appInfos`, { 'fields[appInfos]': 'state' });
26
- const infos = data.data ?? [];
27
- if (infos.length === 0)
28
- throw new Error(`앱 ${appId} 의 appInfo 를 찾지 못했다.`);
29
- const editable = infos.find((i) => {
30
- const s = i.attributes?.state ?? i.attributes?.appStoreState;
31
- return s && s !== 'READY_FOR_DISTRIBUTION' && s !== 'REPLACED_WITH_NEW_INFO';
32
- });
33
- return (editable ?? infos[0]).id;
34
- }
35
24
  export async function getAgeRating(appId) {
36
- const appInfoId = await resolveAppInfoId(appId);
25
+ const { id } = await requireAppInfo(appId);
26
+ return readAppInfoAgeRating(id);
27
+ }
28
+ async function readAppInfoAgeRating(appInfoId) {
37
29
  // 선언 리소스가 아직 없는 앱이 있다 — 그때는 404 다. 에러 대신 "없음"으로 돌려주고
38
30
  // updateAgeRating 이 사람이 읽을 안내를 내도록 한다.
39
31
  try {
@@ -70,7 +62,12 @@ export async function updateAgeRating(args) {
70
62
  await send(V1_BASE, 'PATCH', `/ageRatingDeclarations/${encodePathSegment(current.declarationId)}`, {
71
63
  data: { type: 'ageRatingDeclarations', id: current.declarationId, attributes },
72
64
  });
73
- const after = await getAgeRating(appId);
65
+ const verificationError = `연령등급 변경 요청 후 대상 선언 ${current.declarationId}의 저장 결과를 확인할 수 없습니다.`;
66
+ const after = await readAppInfoAgeRating(current.appInfoId).catch((error) => {
67
+ throw new Error(verificationError, { cause: error });
68
+ });
69
+ if (after.declarationId !== current.declarationId)
70
+ throw new Error(verificationError);
74
71
  return { declarationId: current.declarationId, declaration: after.declaration };
75
72
  }
76
73
  /**
@@ -12,7 +12,8 @@ import fs from 'node:fs';
12
12
  import path from 'node:path';
13
13
  import crypto from 'node:crypto';
14
14
  import { getAuthHeaders } from './auth.js';
15
- import { fetchWithTimeout, HTTP_TRANSFER_TIMEOUT_MS } from '../lib/http.js';
15
+ import { fetchWithTimeout } from '../lib/http.js';
16
+ import { uploadFileParts } from './upload-parts.js';
16
17
  import { encodePathSegment } from '../lib/url-path.js';
17
18
  const BASE = 'https://api.appstoreconnect.apple.com/v1';
18
19
  async function req(pathOrUrl, init = {}) {
@@ -81,33 +82,6 @@ async function ensurePreviewSet(localizationId, previewType) {
81
82
  });
82
83
  return created.data.id;
83
84
  }
84
- async function uploadChunks(absPath, ops) {
85
- const fd = fs.openSync(absPath, 'r');
86
- try {
87
- for (const op of ops) {
88
- // 파일 전체를 메모리에 올리지 않는다 — 동영상은 수백 MB 가 될 수 있다.
89
- const chunk = Buffer.alloc(op.length);
90
- const bytesRead = fs.readSync(fd, chunk, 0, op.length, op.offset);
91
- // Buffer.alloc 은 0 으로 채운다 — 짧게 읽힌 걸 모르고 보내면 **0 패딩이 영상 데이터로**
92
- // 올라가고, PUT 은 성공한 뒤 체크섬 불일치가 한참 뒤 인코딩 실패로 나타난다.
93
- // 여기서 즉시 멈추는 게 그 추적 불가능한 실패보다 낫다.
94
- if (bytesRead !== op.length) {
95
- throw new Error(`파일을 읽는 중 크기가 어긋났다 (offset ${op.offset}: ${op.length} 바이트 요청, ${bytesRead} 읽음). ` +
96
- '업로드 도중 파일이 바뀌었을 수 있다 — 파일을 확인하고 다시 시도할 것.');
97
- }
98
- const headers = {};
99
- for (const h of op.requestHeaders ?? [])
100
- headers[h.name] = h.value;
101
- const res = await fetchWithTimeout(op.url, { method: op.method ?? 'PUT', headers, body: chunk }, HTTP_TRANSFER_TIMEOUT_MS);
102
- if (!res.ok) {
103
- throw new Error(`미리보기 업로드 실패 (offset ${op.offset}): ${res.status} ${await res.text()}`);
104
- }
105
- }
106
- }
107
- finally {
108
- fs.closeSync(fd);
109
- }
110
- }
111
85
  /** 확장자로 추정한 mimeType. Apple 은 없어도 받지만 있으면 처리 실패가 줄어든다. */
112
86
  function guessMimeType(fileName) {
113
87
  const ext = path.extname(fileName).toLowerCase();
@@ -157,7 +131,7 @@ export async function uploadPreview(args) {
157
131
  const ops = reserved.data.attributes?.uploadOperations ?? [];
158
132
  if (ops.length === 0)
159
133
  throw new Error('uploadOperations 가 비어 있다 — Apple 응답 형식 확인 필요.');
160
- await uploadChunks(filePath, ops);
134
+ await uploadFileParts(filePath, ops);
161
135
  // 체크섬은 전체 파일 기준이라 스트리밍으로 계산한다 (메모리에 다 올리지 않는다).
162
136
  const md5 = await new Promise((resolve, reject) => {
163
137
  const hash = crypto.createHash('md5');
@@ -0,0 +1,14 @@
1
+ import { z } from 'zod';
2
+ export declare const appStorePagination: z.ZodObject<{
3
+ links: z.ZodOptional<z.ZodNullable<z.ZodObject<{
4
+ next: z.ZodOptional<z.ZodNullable<z.ZodString>>;
5
+ }, z.core.$strip>>>;
6
+ meta: z.ZodOptional<z.ZodObject<{
7
+ paging: z.ZodOptional<z.ZodObject<{
8
+ total: z.ZodOptional<z.ZodNumber>;
9
+ nextCursor: z.ZodOptional<z.ZodNullable<z.ZodString>>;
10
+ }, z.core.$strip>>;
11
+ }, z.core.$strip>>;
12
+ }, z.core.$strip>;
13
+ export declare function pageIsIncomplete(page: z.infer<typeof appStorePagination>, count: number): boolean;
14
+ export declare function getAppStoreResponse<T>(schema: z.ZodType<T>, path: string, params?: Record<string, string>): Promise<T>;