@yourname168/tiktok 0.1.0 → 0.2.1

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.
package/README.md CHANGED
@@ -53,9 +53,61 @@ Keep session files outside version control. The library does not acquire session
53
53
  `uploadVideo()` uploads video bytes, attaches the explicitly selected products,
54
54
  and publishes. It defaults to **private**; there is no automatic retry.
55
55
  `publishVideo()` publishes an already uploaded `{ videoId, width, height }` asset.
56
- The result is the raw validated response, not a guarantee that moderation or
57
- processing completed. Reuse a known `creationId` and inspect TikTok before
58
- retrying after a timeout; this library does not claim server-side idempotency.
56
+
57
+ ### Publish a photo album
58
+
59
+ ```ts
60
+ await client.publishPhotoAlbum({
61
+ creationId,
62
+ title: '',
63
+ caption: '',
64
+ photos: uploadedPhotos,
65
+ products: [{ productId: 'chosen-product-id', displayName: 'Tên sản phẩm' }],
66
+ productRegistration: 'existing',
67
+ visibility: 'public',
68
+ music: selectedMusic,
69
+ });
70
+ ```
71
+
72
+ Each uploaded photo needs `id`, `uri`, `width` and `height`. Photo file upload
73
+ is outside the library. The optional music metadata contains `id`, `title`,
74
+ `author`, `url` and `endSeconds` from a TikTok sound selected for the post.
75
+ Optional fields are `startSeconds` (defaults to zero) and `album`.
76
+ Use `aiGenerated: true` when applying TikTok's AI-generated label.
77
+ `publishPhotoAlbum()` defaults to private. `publishPrivatePhotoAlbum()` always
78
+ submits private visibility. Both support `coverIndex` with a default of zero.
79
+
80
+ `addShowcaseProducts()` runs the same product registration used by the publish
81
+ methods. Set `productRegistration: 'existing'` for products already registered
82
+ in the account's Showcase. The default is `'add'`. Use the same option on
83
+ `publishVideo()` or `uploadVideo()`.
84
+
85
+ ### Use a TikTok sound in a video
86
+
87
+ Pass `music` to `publishVideo()` or `uploadVideo()` to send a native TikTok
88
+ sound and its edit timeline. Provide the same selected-sound metadata as for
89
+ albums, plus `videoDurationSeconds` and, optionally, `framesPerSecond` (24 by
90
+ default). The timeline keeps the original audio, starts the selected sound at
91
+ the beginning of the video, and trims it to the video duration or end of the
92
+ requested track segment, whichever comes first. It does not re-encode the MP4.
93
+
94
+ ```ts
95
+ await client.uploadVideo({
96
+ videoPath: '/absolute/path/video.mp4',
97
+ caption: '',
98
+ visibility: 'private',
99
+ music: { ...selectedMusic, videoDurationSeconds: 10, framesPerSecond: 24 },
100
+ });
101
+ ```
102
+
103
+ Use metadata from a sound available to the posting account. A TikTok music page
104
+ link identifies a track and needs to be resolved to the TikTok playback URL and
105
+ metadata before this API call. The video request shape was checked against
106
+ TikTok Studio. Playback of the linked sound after API publication is unverified.
107
+
108
+ The publish response is TikTok's raw acknowledgement. Check the published item
109
+ for review status, visibility and whether the product anchor renders. Reuse a known
110
+ `creationId` and inspect TikTok before retrying after a timeout.
59
111
 
60
112
  Optional `coverUri` references an already uploaded cover. Uploading a cover file
61
113
  is not ported. Scheduling accepts Unix seconds, at least 20 minutes in the future.
@@ -86,8 +138,10 @@ file-based official upload and interactive OAuth authorization are not ported.
86
138
  and the complete web post body. Signer entropy/time are fixed only in tests.
87
139
  - Offline HTTP tests exercise upload/auth → apply → init → transfer → finish →
88
140
  commit → attach products → publish; account cookies never go to storage hosts.
89
- - **No live account call or real publish has been performed.** Private web APIs
90
- can change independently of the npm package. Treat this as an experimental port.
141
+ - Live account trials accepted image and video submissions with product anchor
142
+ fields. Album approval and public visibility were observed in TikTok Studio.
143
+ Product-card rendering and playback of the selected sound remain unverified.
144
+ TikTok's web API can change independently of this package.
91
145
  - VOD upload currently ports the normal multipart route. Gateway/stream uploads,
92
146
  dynamic slice rules, resume, retries, image upload, messaging, triggers, hashtag
93
147
  lookup and comments are not ported. Storage hosts are restricted in vod-upload.ts.
@@ -98,8 +152,7 @@ file-based official upload and interactive OAuth authorization are not ported.
98
152
  Run from the repository:
99
153
 
100
154
  ```sh
101
- pnpm exec vitest run packages/tiktok/src/tiktok.test.ts
102
- pnpm exec tsc -p packages/tiktok/tsconfig.json --noEmit
155
+ pnpm --filter @gateway/tiktok typecheck
103
156
  ```
104
157
 
105
158
  Workspace consumers import source, as established by repository conventions.
@@ -107,7 +160,7 @@ For installation outside the monorepo, generate a compiled JS + declaration tarb
107
160
 
108
161
  ```sh
109
162
  pnpm --filter @gateway/tiktok pack:portable /absolute/output/directory
110
- npm install /absolute/output/directory/gateway-tiktok-0.1.0.tgz
163
+ npm install /absolute/output/directory/gateway-tiktok-0.2.1.tgz
111
164
  ```
112
165
 
113
166
  Use this portable tarball instead of packing the TypeScript workspace directly:
@@ -120,7 +173,7 @@ To prepare a public release under the npm account scope:
120
173
 
121
174
  ```sh
122
175
  pnpm --filter @gateway/tiktok pack:portable /absolute/output/directory --name @yourname168/tiktok
123
- npm publish /absolute/output/directory/yourname168-tiktok-0.1.0.tgz --access public
176
+ npm publish /absolute/output/directory/yourname168-tiktok-0.2.1.tgz --access public
124
177
  ```
125
178
 
126
179
  The public tarball excludes tests, session files, npm credentials and workspace
package/dist/http.js CHANGED
@@ -33,8 +33,10 @@ export function createHttp(transport = fetch, timeoutMs = 120_000) {
33
33
  const data = object(value);
34
34
  const metadata = data.ResponseMetadata;
35
35
  const apiError = data.error;
36
+ // TikTok's multipart storage endpoint uses 2000 for successful operations.
37
+ const storageSuccess = new URL(url).pathname.startsWith('/upload/v1/') && data.code === 2000;
36
38
  if ((metadata && object(metadata).Error) || (apiError && object(apiError).code !== undefined && object(apiError).code !== 'ok') ||
37
- (data.status_code !== undefined && data.status_code !== 0) || (data.code !== undefined && data.code !== 0)) {
39
+ (data.status_code !== undefined && data.status_code !== 0) || (data.code !== undefined && data.code !== 0 && !storageSuccess)) {
38
40
  throw new Error('TikTok rejected the request');
39
41
  }
40
42
  return data;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { createTikTokWebClient } from './web-client.ts';
2
2
  export { createTikTokContentClient, refreshTikTokToken } from './content-client.ts';
3
3
  export { parseTikTokSession } from './session.ts';
4
- export { createWebPostBody, productAnchors } from './post-body.ts';
4
+ export { createPhotoPostBody, createWebPostBody, productAnchors } from './post-body.ts';
5
5
  export type { TikTokSession } from './session.ts';
6
- export type { ProductAnchor, UploadedVideo, WebPostOptions } from './post-body.ts';
6
+ export type { PhotoAlbumMusic, PhotoPostOptions, PrivatePhotoPostOptions, ProductAnchor, UploadedPhoto, UploadedVideo, VideoPostMusic, WebPostOptions } from './post-body.ts';
7
7
  export type { HttpTransport } from './http.ts';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export { createTikTokWebClient } from "./web-client.js";
2
2
  export { createTikTokContentClient, refreshTikTokToken } from "./content-client.js";
3
3
  export { parseTikTokSession } from "./session.js";
4
- export { createWebPostBody, productAnchors } from "./post-body.js";
4
+ export { createPhotoPostBody, createWebPostBody, productAnchors } from "./post-body.js";
@@ -7,6 +7,39 @@ export interface UploadedVideo {
7
7
  width: number;
8
8
  height: number;
9
9
  }
10
+ export interface UploadedPhoto {
11
+ id: string;
12
+ uri: string;
13
+ width: number;
14
+ height: number;
15
+ }
16
+ export interface PhotoAlbumMusic {
17
+ id: string;
18
+ title: string;
19
+ author: string;
20
+ url: string;
21
+ startSeconds?: number;
22
+ endSeconds: number;
23
+ album?: string;
24
+ }
25
+ export interface VideoPostMusic extends PhotoAlbumMusic {
26
+ videoDurationSeconds: number;
27
+ framesPerSecond?: number;
28
+ }
29
+ export interface PrivatePhotoPostOptions {
30
+ creationId: string;
31
+ title: string;
32
+ caption: string;
33
+ photos: readonly UploadedPhoto[];
34
+ products: ProductAnchor[];
35
+ coverIndex?: number;
36
+ music?: PhotoAlbumMusic;
37
+ aiGenerated?: boolean;
38
+ productRegistration?: 'add' | 'existing';
39
+ }
40
+ export interface PhotoPostOptions extends PrivatePhotoPostOptions {
41
+ visibility?: 'public' | 'friends' | 'private';
42
+ }
10
43
  export interface WebPostOptions {
11
44
  creationId: string;
12
45
  caption: string;
@@ -16,6 +49,8 @@ export interface WebPostOptions {
16
49
  allowComments?: boolean;
17
50
  scheduleTimeSeconds?: number;
18
51
  products?: ProductAnchor[];
52
+ productRegistration?: 'add' | 'existing';
53
+ music?: VideoPostMusic;
19
54
  }
20
55
  export declare function productAnchors(products: ProductAnchor[]): {
21
56
  type: number;
@@ -49,6 +84,8 @@ export declare function createWebPostBody(input: WebPostOptions): {
49
84
  };
50
85
  }[];
51
86
  vedit_common_info: {
87
+ application?: number;
88
+ tiktok_snap_shot_lite_params?: string;
52
89
  draft: string;
53
90
  video_id: string;
54
91
  };
@@ -66,17 +103,6 @@ export declare function createWebPostBody(input: WebPostOptions): {
66
103
  video_id: string;
67
104
  is_long_video: number;
68
105
  single_post_feature_info: {
69
- text: string;
70
- text_extra: {
71
- tag_id: string;
72
- user_id: string;
73
- start: number;
74
- end: number;
75
- type: number;
76
- hashtag_name: string | undefined;
77
- }[];
78
- markup_text: string;
79
- music_info: {};
80
106
  cover_info: {
81
107
  frame_duration: number;
82
108
  blob_url: string;
@@ -92,6 +118,177 @@ export declare function createWebPostBody(input: WebPostOptions): {
92
118
  cloud_edit_video_height: number;
93
119
  cloud_edit_video_width: number;
94
120
  cloud_edit_is_use_video_canvas: boolean;
121
+ music_info: {};
122
+ vedit_segment_info?: {
123
+ start_time: number;
124
+ end_time: number;
125
+ };
126
+ has_original_audio?: number;
127
+ is_upload_audio_track?: boolean;
128
+ video_track_time_range_list?: {
129
+ start_time_in_ms: number;
130
+ end_time_in_ms: number;
131
+ }[];
132
+ text: string;
133
+ text_extra: {
134
+ tag_id: string;
135
+ user_id: string;
136
+ start: number;
137
+ end: number;
138
+ type: number;
139
+ hashtag_name: string | undefined;
140
+ }[];
141
+ markup_text: string;
142
+ };
143
+ }[];
144
+ };
145
+ export declare function createPhotoPostBody(input: PhotoPostOptions): {
146
+ feature_common_info_list: {
147
+ aigc_info: {
148
+ aigc_label_type: number;
149
+ };
150
+ org_game_post_use_store_region: boolean;
151
+ privacy_setting_info: {
152
+ allow_comment: number;
153
+ allow_duet: number;
154
+ allow_stitch: number;
155
+ allow_content_reuse: number;
156
+ allow_ai_remix: number;
157
+ visibility_type: number;
158
+ };
159
+ draft_id: string;
160
+ tcm_params: string;
161
+ anchors: {
162
+ type: number;
163
+ keyword: string;
164
+ content: {
165
+ add_from: number;
166
+ keyword: string;
167
+ product_id: string;
168
+ };
169
+ }[];
170
+ }[];
171
+ post_common_info: {
172
+ creation_id: string;
173
+ enter_post_page_from: number;
174
+ post_type: number;
175
+ };
176
+ single_post_req_list: {
177
+ batch_index: number;
178
+ aweme_type: number;
179
+ image_post_content: {
180
+ title: string;
181
+ images: {
182
+ id: string;
183
+ uri: string;
184
+ width_px: number;
185
+ height_px: number;
186
+ }[];
187
+ cover: {
188
+ id: string;
189
+ uri: string;
190
+ width_px: number;
191
+ height_px: number;
192
+ } | undefined;
193
+ };
194
+ single_post_feature_info: {
195
+ music_info?: {
196
+ music_id_string: string;
197
+ music_title: string;
198
+ music_author: string;
199
+ music_url: string;
200
+ music_begin_time: number;
201
+ music_end_time: number;
202
+ origin_volume: string;
203
+ music_volume: string;
204
+ music_album: string;
205
+ music_type: number;
206
+ };
207
+ text: string;
208
+ text_extra: {
209
+ tag_id: string;
210
+ user_id: string;
211
+ start: number;
212
+ end: number;
213
+ type: number;
214
+ hashtag_name: string | undefined;
215
+ }[];
216
+ markup_text: string;
217
+ };
218
+ }[];
219
+ };
220
+ export declare function createPrivatePhotoPostBody(input: PrivatePhotoPostOptions): {
221
+ feature_common_info_list: {
222
+ aigc_info: {
223
+ aigc_label_type: number;
224
+ };
225
+ org_game_post_use_store_region: boolean;
226
+ privacy_setting_info: {
227
+ allow_comment: number;
228
+ allow_duet: number;
229
+ allow_stitch: number;
230
+ allow_content_reuse: number;
231
+ allow_ai_remix: number;
232
+ visibility_type: number;
233
+ };
234
+ draft_id: string;
235
+ tcm_params: string;
236
+ anchors: {
237
+ type: number;
238
+ keyword: string;
239
+ content: {
240
+ add_from: number;
241
+ keyword: string;
242
+ product_id: string;
243
+ };
244
+ }[];
245
+ }[];
246
+ post_common_info: {
247
+ creation_id: string;
248
+ enter_post_page_from: number;
249
+ post_type: number;
250
+ };
251
+ single_post_req_list: {
252
+ batch_index: number;
253
+ aweme_type: number;
254
+ image_post_content: {
255
+ title: string;
256
+ images: {
257
+ id: string;
258
+ uri: string;
259
+ width_px: number;
260
+ height_px: number;
261
+ }[];
262
+ cover: {
263
+ id: string;
264
+ uri: string;
265
+ width_px: number;
266
+ height_px: number;
267
+ } | undefined;
268
+ };
269
+ single_post_feature_info: {
270
+ music_info?: {
271
+ music_id_string: string;
272
+ music_title: string;
273
+ music_author: string;
274
+ music_url: string;
275
+ music_begin_time: number;
276
+ music_end_time: number;
277
+ origin_volume: string;
278
+ music_volume: string;
279
+ music_album: string;
280
+ music_type: number;
281
+ };
282
+ text: string;
283
+ text_extra: {
284
+ tag_id: string;
285
+ user_id: string;
286
+ start: number;
287
+ end: number;
288
+ type: number;
289
+ hashtag_name: string | undefined;
290
+ }[];
291
+ markup_text: string;
95
292
  };
96
293
  }[];
97
294
  };
package/dist/post-body.js CHANGED
@@ -5,6 +5,18 @@ export function productAnchors(products) {
5
5
  return { type: 33, keyword, content: { add_from: 2, keyword, product_id: string(product.productId, 'productId') } };
6
6
  });
7
7
  }
8
+ function captionFields(caption) {
9
+ const matches = [...caption.matchAll(/#(\w+)/g)];
10
+ const text_extra = matches.map((match, index) => ({ tag_id: String(index), user_id: '', start: match.index, end: match.index + match[0].length, type: 1, hashtag_name: match[1] }));
11
+ let markup_text = '';
12
+ let offset = 0;
13
+ matches.forEach((match, index) => {
14
+ markup_text += caption.slice(offset, match.index).replaceAll('\n', '<br>') + `<h id="${index}">${match[0]}</h>`;
15
+ offset = match.index + match[0].length;
16
+ });
17
+ markup_text += caption.slice(offset).replaceAll('\n', '<br>');
18
+ return { text: caption, text_extra, markup_text };
19
+ }
8
20
  export function createWebPostBody(input) {
9
21
  string(input.creationId, 'creationId');
10
22
  string(input.video.videoId, 'videoId');
@@ -17,26 +29,121 @@ export function createWebPostBody(input) {
17
29
  const visibility = input.visibility ?? 'private';
18
30
  if (!['public', 'friends', 'private'].includes(visibility))
19
31
  throw new Error('Invalid visibility');
20
- const matches = [...input.caption.matchAll(/#(\w+)/g)];
21
- const text_extra = matches.map((match, index) => ({ tag_id: String(index), user_id: '', start: match.index, end: match.index + match[0].length, type: 1, hashtag_name: match[1] }));
22
- let markup_text = '';
23
- let offset = 0;
24
- matches.forEach((match, index) => {
25
- markup_text += input.caption.slice(offset, match.index).replaceAll('\n', '<br>') + `<h id="${index}">${match[0]}</h>`;
26
- offset = match.index + match[0].length;
27
- });
28
- markup_text += input.caption.slice(offset).replaceAll('\n', '<br>');
32
+ const audio = input.music ? videoMusicFields(input.video, input.music) : undefined;
29
33
  return {
30
34
  post_common_info: { creation_id: input.creationId, enter_post_page_from: 2, post_type: 3 },
31
35
  feature_common_info_list: [{ schedule_time: schedule, geofencing_regions: [], playlist_name: '', playlist_id: '',
32
36
  tcm_params: '{"commerce_toggle_info":{}}', sound_exemption: 0, anchors: productAnchors(input.products ?? []),
33
- vedit_common_info: { draft: '', video_id: input.video.videoId },
37
+ vedit_common_info: { draft: '', video_id: input.video.videoId, ...audio?.editor },
34
38
  privacy_setting_info: { visibility_type: { public: 0, friends: 2, private: 1 }[visibility], allow_duet: null,
35
39
  allow_stitch: null, allow_comment: input.allowComments === false ? 0 : 1, allow_content_reuse: 1 }, content_check_id: '' }],
36
40
  single_post_req_list: [{ batch_index: 0, video_id: input.video.videoId, is_long_video: 0,
37
- single_post_feature_info: { text: input.caption, text_extra, markup_text, music_info: {},
41
+ single_post_feature_info: { ...captionFields(input.caption), music_info: {}, ...audio?.post,
38
42
  cover_info: { frame_duration: 0, blob_url: '', cover_width: input.video.width, cover_height: input.video.height,
39
43
  cover_type: 2, crop_type: 2, isAutoCropFirstFrame: true, cover_uri: input.coverUri ?? '', isProcessingInitialCover: false },
40
44
  poster_delay: 0, cloud_edit_video_height: input.video.height, cloud_edit_video_width: input.video.width, cloud_edit_is_use_video_canvas: false } }],
41
45
  };
42
46
  }
47
+ function musicInfo(music) {
48
+ const start = music.startSeconds ?? 0;
49
+ if (!Number.isFinite(start) || !Number.isFinite(music.endSeconds) || start < 0 || music.endSeconds <= start) {
50
+ throw new Error('Invalid music time range');
51
+ }
52
+ const url = new URL(music.url);
53
+ if (url.protocol !== 'https:' || url.username || url.password)
54
+ throw new Error('Invalid music URL');
55
+ return {
56
+ music_id_string: string(music.id, 'music id'),
57
+ music_title: string(music.title, 'music title'),
58
+ music_author: music.author,
59
+ music_url: url.href,
60
+ music_begin_time: start,
61
+ music_end_time: music.endSeconds,
62
+ origin_volume: '100',
63
+ music_volume: '100',
64
+ music_album: music.album ?? '',
65
+ music_type: 1,
66
+ };
67
+ }
68
+ function videoMusicFields(video, music) {
69
+ const track = musicInfo(music);
70
+ const duration = Math.round(music.videoDurationSeconds * 1000);
71
+ const framesPerSecond = music.framesPerSecond ?? 24;
72
+ const start = Math.round(track.music_begin_time * 1000);
73
+ const end = Math.min(Math.round(track.music_end_time * 1000), start + duration);
74
+ if (![duration, start, end].every(Number.isSafeInteger) || duration < 1 || end <= start ||
75
+ !Number.isFinite(framesPerSecond) || framesPerSecond <= 0) {
76
+ throw new Error('Invalid video music timeline');
77
+ }
78
+ const snapshot = {
79
+ Elements: [
80
+ {
81
+ Type: 'video', Source: `vid://${video.videoId}`, StartIndex: 0, StartTime: 0, EndTime: duration,
82
+ Volume: 1, Background: { Type: 'color', Color: '#000000FF' }, OffsetX: 0, OffsetY: 0,
83
+ Rotate: 0, Scale: 1, Alpha: 1,
84
+ },
85
+ {
86
+ Type: 'audio', Source: track.music_url, StartTime: 0, EndTime: end - start, StartIndex: 0,
87
+ StartOffset: start, EndIndex: 0, EndOffset: end, Volume: 1, FadeIn: 0, FadeOut: 0,
88
+ },
89
+ ],
90
+ GlobalElements: [],
91
+ OutputInfo: { Format: 'mp4', Width: video.width, Height: video.height, Fps: framesPerSecond, Duration: duration, FallbackFonts: [] },
92
+ };
93
+ return {
94
+ editor: { application: 2, tiktok_snap_shot_lite_params: JSON.stringify(snapshot) },
95
+ post: {
96
+ music_info: { ...track, music_begin_time: start, music_end_time: end },
97
+ vedit_segment_info: { start_time: 0, end_time: duration },
98
+ has_original_audio: 1,
99
+ is_upload_audio_track: true,
100
+ video_track_time_range_list: [{ start_time_in_ms: 0, end_time_in_ms: duration }],
101
+ },
102
+ };
103
+ }
104
+ export function createPhotoPostBody(input) {
105
+ string(input.creationId, 'creationId');
106
+ if (!input.products.length)
107
+ throw new Error('At least one product is required');
108
+ if (!input.photos.length || input.photos.length > 35)
109
+ throw new Error('Provide 1 to 35 photos');
110
+ const visibility = input.visibility ?? 'private';
111
+ if (!['public', 'friends', 'private'].includes(visibility))
112
+ throw new Error('Invalid visibility');
113
+ const photos = input.photos.map(photo => {
114
+ if (![photo.width, photo.height].every(n => Number.isSafeInteger(n) && n > 0)) {
115
+ throw new Error('Invalid photo dimensions');
116
+ }
117
+ return { id: string(photo.id, 'photo id'), uri: string(photo.uri, 'photo uri'), width_px: photo.width, height_px: photo.height };
118
+ });
119
+ const coverIndex = input.coverIndex ?? 0;
120
+ if (!Number.isInteger(coverIndex) || coverIndex < 0 || coverIndex >= photos.length)
121
+ throw new Error('Invalid photo cover index');
122
+ const cover = photos[coverIndex];
123
+ return {
124
+ feature_common_info_list: [{
125
+ aigc_info: { aigc_label_type: input.aiGenerated === true ? 1 : 0 },
126
+ org_game_post_use_store_region: false,
127
+ privacy_setting_info: {
128
+ allow_comment: 0, allow_duet: 0, allow_stitch: 0, allow_content_reuse: 0, allow_ai_remix: 2,
129
+ visibility_type: { public: 0, friends: 2, private: 1 }[visibility],
130
+ },
131
+ draft_id: '',
132
+ tcm_params: '{"commerce_toggle_info":{}}',
133
+ anchors: productAnchors(input.products),
134
+ }],
135
+ post_common_info: { creation_id: input.creationId, enter_post_page_from: 8, post_type: 4 },
136
+ single_post_req_list: [{
137
+ batch_index: 0,
138
+ aweme_type: 150,
139
+ image_post_content: { title: input.title, images: photos, cover },
140
+ single_post_feature_info: {
141
+ ...captionFields(input.caption),
142
+ ...(input.music ? { music_info: musicInfo(input.music) } : {}),
143
+ },
144
+ }],
145
+ };
146
+ }
147
+ export function createPrivatePhotoPostBody(input) {
148
+ return createPhotoPostBody({ ...input, visibility: 'private' });
149
+ }
package/dist/session.js CHANGED
@@ -13,11 +13,18 @@ function stringMap(value) {
13
13
  export function parseTikTokSession(value) {
14
14
  let input = value;
15
15
  if (typeof input === 'string') {
16
- try {
17
- input = JSON.parse(input);
16
+ const session = input.trim();
17
+ const hasSessionCookie = session.split(';').some(pair => /^sessionid=[^\s;]+$/.test(pair.trim()));
18
+ if (hasSessionCookie && !/[\r\n]/.test(session) && /^[A-Za-z0-9_~-]+=/.test(session)) {
19
+ input = { headers: { cookie: session } };
18
20
  }
19
- catch {
20
- throw new Error('Invalid TikTok session JSON');
21
+ else {
22
+ try {
23
+ input = JSON.parse(session);
24
+ }
25
+ catch {
26
+ throw new Error('Invalid TikTok session JSON or cookie');
27
+ }
21
28
  }
22
29
  }
23
30
  const outer = object(input), http = object(outer.http ?? outer);
@@ -31,7 +31,9 @@ export async function uploadVodVideo(input) {
31
31
  const store = first(node.StoreInfos);
32
32
  const host = new URL(`https://${string(node.UploadHost, 'UploadHost')}`);
33
33
  // Session cookies belong to TikTok, never to the separate upload host.
34
- if (!host.hostname.endsWith('.tiktok.com') && !host.hostname.endsWith('.tiktokv.com') && !host.hostname.endsWith('.byteoversea.com') && !host.hostname.endsWith('.ibyteimg.com'))
34
+ const allowedDomains = ['.tiktok.com', '.tiktokv.com', '.tiktokcdn.com', '.byteoversea.com', '.ibyteimg.com'];
35
+ if (host.username || host.password || host.port || host.pathname !== '/' || host.search || host.hash ||
36
+ !allowedDomains.some(domain => host.hostname.endsWith(domain)))
35
37
  throw new Error('Unsupported upload host');
36
38
  const uploadUrl = new URL(`/upload/v1/${string(store.StoreUri, 'StoreUri')}`, host);
37
39
  const headers = { Authorization: string(store.Auth, 'upload Auth'), 'X-Storage-U': encodeURIComponent(input.userId) };
@@ -1,5 +1,5 @@
1
1
  import type { HttpTransport } from './http.ts';
2
- import type { WebPostOptions } from './post-body.ts';
2
+ import type { PhotoPostOptions, PrivatePhotoPostOptions, ProductAnchor, WebPostOptions } from './post-body.ts';
3
3
  export declare function createTikTokWebClient(options: {
4
4
  session: unknown;
5
5
  transport?: HttpTransport;
@@ -15,6 +15,7 @@ export declare function createTikTokWebClient(options: {
15
15
  title: string;
16
16
  raw: import("./http.ts").JsonObject;
17
17
  }[]>;
18
+ addShowcaseProducts: (products: ProductAnchor[]) => Promise<import("./http.ts").JsonObject | undefined>;
18
19
  getUploadToken: () => Promise<{
19
20
  currentTime?: number;
20
21
  accessKeyId: string;
@@ -22,6 +23,8 @@ export declare function createTikTokWebClient(options: {
22
23
  sessionToken: string;
23
24
  }>;
24
25
  publishVideo: (input: WebPostOptions) => Promise<import("./http.ts").JsonObject>;
26
+ publishPhotoAlbum(input: PhotoPostOptions): Promise<import("./http.ts").JsonObject>;
27
+ publishPrivatePhotoAlbum(input: PrivatePhotoPostOptions): Promise<import("./http.ts").JsonObject>;
25
28
  uploadVideo(input: Omit<WebPostOptions, "creationId" | "video"> & {
26
29
  videoPath: string;
27
30
  creationId?: string;
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { createHttp, object, string } from "./http.js";
3
3
  import { parseTikTokSession } from "./session.js";
4
- import { createWebPostBody } from "./post-body.js";
4
+ import { createPhotoPostBody, createPrivatePhotoPostBody, createWebPostBody } from "./post-body.js";
5
5
  import { signWebPost } from "./sign-web-request.js";
6
6
  import { uploadVodVideo } from "./vod-upload.js";
7
7
  export function createTikTokWebClient(options) {
@@ -18,24 +18,30 @@ export function createTikTokWebClient(options) {
18
18
  return { accessKeyId: string(token.access_key_id, 'access_key_id'), secretAccessKey: string(token.secret_acess_key ?? token.secret_access_key, 'secret_access_key'),
19
19
  sessionToken: string(token.session_token, 'session_token'), ...(typeof token.current_time === 'number' ? { currentTime: token.current_time } : {}) };
20
20
  }
21
- async function attachProducts(products) {
21
+ async function addShowcaseProducts(products) {
22
22
  if (!products.length)
23
23
  return;
24
24
  const url = `https://shop.tiktok.com/aweme/v1/oec/content/creator/products?aid=1180&carrier_region=${carrierRegion}`;
25
25
  await request(url, { method: 'OPTIONS', headers });
26
- await request(url, { method: 'POST', headers: { ...headers, 'content-type': 'application/json' },
26
+ return request(url, { method: 'POST', headers: { ...headers, 'content-type': 'application/json' },
27
27
  body: JSON.stringify({ add_targets: [5], products: products.map(p => ({ product_id: string(p.productId, 'productId') })) }) });
28
28
  }
29
+ async function publishPost(body, products, registration = 'add') {
30
+ if (registration !== 'add' && registration !== 'existing')
31
+ throw new Error('Invalid product registration mode');
32
+ // Validate/sign before mutating the showcase.
33
+ const query = signWebPost(session, body, now());
34
+ if (registration === 'add')
35
+ await addShowcaseProducts(products);
36
+ return request(`https://www.tiktok.com/tiktok/web/project/post/v1/?${query}`, { method: 'POST',
37
+ headers: { ...headers, 'content-type': 'application/json', origin: 'https://www.tiktok.com' }, body });
38
+ }
29
39
  async function publishVideo(input) {
30
40
  const body = JSON.stringify(createWebPostBody(input));
31
41
  const schedule = input.scheduleTimeSeconds ?? 0;
32
42
  if (schedule > 0 && schedule < Math.floor(now() / 1000) + 1200)
33
43
  throw new Error('Schedule must be at least 20 minutes ahead');
34
- // Validate/sign before mutating the showcase.
35
- const query = signWebPost(session, body, now());
36
- await attachProducts(input.products ?? []);
37
- return request(`https://www.tiktok.com/tiktok/web/project/post/v1/?${query}`, { method: 'POST',
38
- headers: { ...headers, 'content-type': 'application/json', origin: 'https://www.tiktok.com' }, body });
44
+ return publishPost(body, input.products ?? [], input.productRegistration);
39
45
  }
40
46
  return {
41
47
  async getShowcaseProducts({ count = 6, offset = 0 } = {}) {
@@ -47,8 +53,15 @@ export function createTikTokWebClient(options) {
47
53
  throw new Error('Missing products array');
48
54
  return products.map(value => { const p = object(value); return { productId: string(p.product_id, 'product_id'), title: string(p.title, 'title'), raw: p }; });
49
55
  },
56
+ addShowcaseProducts,
50
57
  getUploadToken,
51
58
  publishVideo,
59
+ async publishPhotoAlbum(input) {
60
+ return publishPost(JSON.stringify(createPhotoPostBody(input)), input.products, input.productRegistration);
61
+ },
62
+ async publishPrivatePhotoAlbum(input) {
63
+ return publishPost(JSON.stringify(createPrivatePhotoPostBody(input)), input.products, input.productRegistration);
64
+ },
52
65
  async uploadVideo(input) {
53
66
  // Validate product anchors/caption/options before sending video bytes.
54
67
  createWebPostBody({ ...input, creationId: input.creationId ?? 'validate', video: { videoId: 'validate', width: 1, height: 1 } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yourname168/tiktok",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Experimental direct TikTok web-session/Shop and official Content Posting API clients, with TypeScript types and no runtime dependencies.",
5
5
  "license": "MIT",
6
6
  "type": "module",