@posty5/social-publisher-post 4.2.0 → 5.0.0

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/dist/index.js CHANGED
@@ -11747,6 +11747,12 @@ var require_follow_redirects = __commonJS({
11747
11747
  RedirectableRequest.prototype._sanitizeOptions = function(options) {
11748
11748
  if (!options.headers) {
11749
11749
  options.headers = {};
11750
+ } else if (Array.isArray(options.headers)) {
11751
+ var headerList = options.headers;
11752
+ options.headers = {};
11753
+ for (var i = 0; i < headerList.length; i += 2) {
11754
+ options.headers[headerList[i]] = headerList[i + 1];
11755
+ }
11750
11756
  }
11751
11757
  if (!isArray2(options.sensitiveHeaders)) {
11752
11758
  options.sensitiveHeaders = [];
@@ -12021,7 +12027,7 @@ var require_follow_redirects = __commonJS({
12021
12027
  return URL2 && value instanceof URL2;
12022
12028
  }
12023
12029
  function escapeRegex(regex) {
12024
- return regex.replace(/[\]\\/()*+?.$]/g, "\\$&");
12030
+ return regex.replace(/[[\]\\/()*+?.^$|]/g, "\\$&");
12025
12031
  }
12026
12032
  module.exports = wrap({ http: http3, https: https2 });
12027
12033
  module.exports.wrap = wrap;
@@ -17894,6 +17900,20 @@ var ServerError = class extends Posty5Error {
17894
17900
  this.name = "ServerError";
17895
17901
  }
17896
17902
  };
17903
+ var ConflictError = class extends Posty5Error {
17904
+ constructor(message = "The document was changed by someone else", currentVersion = -1, resourceId = "", details) {
17905
+ super(message, "VERSION_CONFLICT", 409, details);
17906
+ this.name = "ConflictError";
17907
+ this.currentVersion = currentVersion;
17908
+ this.resourceId = resourceId;
17909
+ }
17910
+ };
17911
+ var VersionRequiredError = class extends Posty5Error {
17912
+ constructor(message = "The document version is required", details) {
17913
+ super(message, "VERSION_REQUIRED", 428, details);
17914
+ this.name = "VersionRequiredError";
17915
+ }
17916
+ };
17897
17917
  function transformError(error) {
17898
17918
  if (error instanceof Posty5Error) {
17899
17919
  return error;
@@ -17918,6 +17938,22 @@ function transformError(error) {
17918
17938
  return new AuthorizationError(message, details);
17919
17939
  case 404:
17920
17940
  return new NotFoundError(message, details);
17941
+ case 409: {
17942
+ const body = data;
17943
+ if (body?.code === "VERSION_CONFLICT") {
17944
+ const result = body?.result ?? {};
17945
+ const current = Number(result.currentVersion ?? body?.currentVersion);
17946
+ return new ConflictError(
17947
+ message,
17948
+ Number.isFinite(current) ? current : -1,
17949
+ String(result._id ?? body?._id ?? ""),
17950
+ details
17951
+ );
17952
+ }
17953
+ return new Posty5Error(message, body?.code, status, details);
17954
+ }
17955
+ case 428:
17956
+ return new VersionRequiredError(message, details);
17921
17957
  case 429:
17922
17958
  const retryAfter2 = axiosError.response.headers["retry-after"];
17923
17959
  return new RateLimitError(
@@ -17939,6 +17975,67 @@ function transformError(error) {
17939
17975
  }
17940
17976
  return new Posty5Error("An unknown error occurred", void 0, void 0, { originalError: error });
17941
17977
  }
17978
+ var CORE_VERSION = "5.0.0";
17979
+ var DEFAULT_BASE_URL = "https://api.posty5.com";
17980
+ var DEFAULT_TIMEOUT_MS = 3e4;
17981
+ var DEFAULT_MAX_RETRIES = 3;
17982
+ var DEFAULT_RETRY_DELAY_MS = 1e3;
17983
+ var CLIENT_HEADER_NAME = "X-Posty5-Client";
17984
+ var SDK_CLIENT_NAME = "posty5-npm";
17985
+ var SDK_CLIENT_ID = `${SDK_CLIENT_NAME}/${CORE_VERSION}`;
17986
+ var DEFAULT_CREATED_FROM = "npmPackage";
17987
+ var IDEMPOTENT_METHODS = ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"];
17988
+ var NEVER_CONNECTED_ERROR_CODES = ["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH"];
17989
+ var IF_MATCH_HEADER = "If-Match";
17990
+ var CONCURRENCY_REPORT_HEADER = "X-Posty5-Concurrency";
17991
+ var CONCURRENCY_REPORT_MISSING_VERSION = "missing-version";
17992
+ var NON_RETRYABLE_VERSION_STATUSES = [409, 428];
17993
+ function assertVersion(version, name = "version") {
17994
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 0) {
17995
+ throw new TypeError(`Posty5: \`${name}\` must be a non-negative integer (the document's __v), got ${String(version)}`);
17996
+ }
17997
+ }
17998
+ function ifMatchHeader(version) {
17999
+ assertVersion(version);
18000
+ return `"${version}"`;
18001
+ }
18002
+ function hasIfMatch(headers) {
18003
+ if (!headers) return false;
18004
+ if (typeof headers.get === "function") {
18005
+ const value = headers.get(IF_MATCH_HEADER);
18006
+ if (value !== void 0 && value !== null) return true;
18007
+ }
18008
+ return Object.keys(headers).some((key) => key.toLowerCase() === IF_MATCH_HEADER.toLowerCase());
18009
+ }
18010
+ function withVersion(response, id) {
18011
+ const result = response.result && typeof response.result === "object" ? { ...response.result } : {};
18012
+ if (id !== void 0 && result._id === void 0) result._id = id;
18013
+ if (typeof response.version === "number") result.__v = response.version;
18014
+ return result;
18015
+ }
18016
+ var missingVersionWarned = false;
18017
+ function warnOnMissingVersion(headers, method, url2) {
18018
+ if (missingVersionWarned || !headers) return false;
18019
+ const value = typeof headers.get === "function" ? headers.get(CONCURRENCY_REPORT_HEADER) : headers[CONCURRENCY_REPORT_HEADER.toLowerCase()];
18020
+ if (String(value ?? "").toLowerCase() !== CONCURRENCY_REPORT_MISSING_VERSION) return false;
18021
+ missingVersionWarned = true;
18022
+ console.warn(
18023
+ `[Posty5 SDK] ${String(method || "").toUpperCase()} ${url2 ?? ""} was sent without a document version; the API will refuse it once versions are enforced. Please report this SDK bug.`
18024
+ );
18025
+ return true;
18026
+ }
18027
+ function shouldRetryRequest(error) {
18028
+ const method = String(error?.config?.method || "").toUpperCase();
18029
+ const idempotent = IDEMPOTENT_METHODS.includes(method);
18030
+ const status = error?.response?.status;
18031
+ if (hasIfMatch(error?.config?.headers)) return false;
18032
+ if (status !== void 0 && NON_RETRYABLE_VERSION_STATUSES.includes(status)) return false;
18033
+ if (status === void 0) {
18034
+ if (idempotent) return esm_default.isNetworkError(error);
18035
+ return NEVER_CONNECTED_ERROR_CODES.includes(String(error?.code || ""));
18036
+ }
18037
+ return idempotent && status >= 500;
18038
+ }
17942
18039
  function parseFileName(disposition) {
17943
18040
  if (!disposition) return void 0;
17944
18041
  const match = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(disposition);
@@ -17952,28 +18049,27 @@ function parseFileName(disposition) {
17952
18049
  var HttpClient = class {
17953
18050
  constructor(config = {}) {
17954
18051
  this.config = {
17955
- timeout: 3e4,
17956
- maxRetries: 3,
17957
- retryDelay: 1e3,
18052
+ timeout: DEFAULT_TIMEOUT_MS,
18053
+ maxRetries: DEFAULT_MAX_RETRIES,
18054
+ retryDelay: DEFAULT_RETRY_DELAY_MS,
17958
18055
  ...config,
17959
- baseUrl: config.baseUrl || process.env.POSTY5_BASE_URL || "https://api.posty5.com"
18056
+ baseUrl: config.baseUrl || process.env.POSTY5_BASE_URL || DEFAULT_BASE_URL
17960
18057
  };
17961
18058
  this.axiosInstance = axios_default.create({
17962
18059
  baseURL: this.config.baseUrl,
17963
18060
  timeout: this.config.timeout,
17964
18061
  headers: {
17965
18062
  "Content-Type": "application/json",
18063
+ [CLIENT_HEADER_NAME]: SDK_CLIENT_ID,
17966
18064
  ...this.config.headers
17967
18065
  }
17968
18066
  });
17969
18067
  esm_default(this.axiosInstance, {
17970
- retries: this.config.maxRetries || 3,
18068
+ retries: this.config.maxRetries ?? DEFAULT_MAX_RETRIES,
17971
18069
  retryDelay: (retryCount) => {
17972
- return retryCount * (this.config.retryDelay || 1e3);
18070
+ return retryCount * (this.config.retryDelay ?? DEFAULT_RETRY_DELAY_MS);
17973
18071
  },
17974
- retryCondition: (error) => {
17975
- return esm_default.isNetworkOrIdempotentRequestError(error) || error.response?.status !== void 0 && error.response.status >= 500;
17976
- }
18072
+ retryCondition: shouldRetryRequest
17977
18073
  });
17978
18074
  this.axiosInstance.interceptors.request.use(
17979
18075
  (config2) => {
@@ -18002,6 +18098,7 @@ var HttpClient = class {
18002
18098
  );
18003
18099
  this.axiosInstance.interceptors.response.use(
18004
18100
  (response) => {
18101
+ warnOnMissingVersion(response.headers, response.config?.method, response.config?.url);
18005
18102
  if (this.config.debug) {
18006
18103
  console.log("[Posty5 SDK] Response:", {
18007
18104
  status: response.status,
@@ -18018,6 +18115,10 @@ var HttpClient = class {
18018
18115
  }
18019
18116
  );
18020
18117
  }
18118
+ /** The `createdFrom` label the clients stamp on records they create. */
18119
+ get createdFrom() {
18120
+ return this.config.createdFrom || DEFAULT_CREATED_FROM;
18121
+ }
18021
18122
  /**
18022
18123
  * Set or update the API key
18023
18124
  */
@@ -18122,11 +18223,18 @@ var HttpClient = class {
18122
18223
  }
18123
18224
  const axiosConfig = {};
18124
18225
  if (config.headers) {
18125
- axiosConfig.headers = config.headers;
18226
+ axiosConfig.headers = { ...config.headers };
18227
+ }
18228
+ if (config.version !== void 0) {
18229
+ axiosConfig.headers = { ...axiosConfig.headers || {}, [IF_MATCH_HEADER]: ifMatchHeader(config.version) };
18230
+ axiosConfig["axios-retry"] = { retries: 0 };
18126
18231
  }
18127
18232
  if (config.params) {
18128
18233
  axiosConfig.params = config.params;
18129
18234
  }
18235
+ if (config.data !== void 0) {
18236
+ axiosConfig.data = config.data;
18237
+ }
18130
18238
  if (config.timeout) {
18131
18239
  axiosConfig.timeout = config.timeout;
18132
18240
  }
@@ -18406,17 +18514,20 @@ var SocialPublisherPostClient = class {
18406
18514
  * cannot be removed programmatically and no credits are charged.
18407
18515
  *
18408
18516
  * @param id - Post ID
18409
- * @returns Per-platform removal results
18517
+ * @param version - The post's `__v` as you read it. A stale one throws `ConflictError`.
18518
+ * @returns Per-platform removal results, `__v` set to the post's new version
18410
18519
  *
18411
18520
  * @example
18412
18521
  * ```ts
18413
- * const { results } = await client.removePost("post_123");
18522
+ * const post = await client.getStatus("post_123");
18523
+ * const { results } = await client.removePost("post_123", post.__v);
18414
18524
  * // results.youtube?.success === true
18415
18525
  * ```
18416
18526
  */
18417
- async removePost(id) {
18418
- const response = await this.http.post(`${this.basePath}/${id}/remove`, {});
18419
- return response.result;
18527
+ async removePost(id, version) {
18528
+ assertVersion(version);
18529
+ const response = await this.http.post(`${this.basePath}/${id}/remove`, {}, { version });
18530
+ return withVersion(response, id);
18420
18531
  }
18421
18532
  /**
18422
18533
  * Get next and previous post IDs
@@ -18435,7 +18546,7 @@ var SocialPublisherPostClient = class {
18435
18546
  const url2 = id ? `${this.basePath}/short-video/workspace/by-file/${id}` : `${this.basePath}/short-video/workspace/by-file`;
18436
18547
  const response = await this.http.post(url2, {
18437
18548
  ...data,
18438
- createdFrom: "npmPackage"
18549
+ createdFrom: this.http.createdFrom
18439
18550
  });
18440
18551
  return response.result?._id;
18441
18552
  }
@@ -18448,7 +18559,7 @@ var SocialPublisherPostClient = class {
18448
18559
  const url2 = id ? `${this.basePath}/short-video/workspace/by-url/${id}` : `${this.basePath}/short-video/workspace/by-url`;
18449
18560
  const response = await this.http.post(url2, {
18450
18561
  ...data,
18451
- createdFrom: "npmPackage"
18562
+ createdFrom: this.http.createdFrom
18452
18563
  });
18453
18564
  return response.result?._id;
18454
18565
  }
@@ -18461,7 +18572,7 @@ var SocialPublisherPostClient = class {
18461
18572
  const url2 = id ? `${this.basePath}/short-video/account/by-file/${id}` : `${this.basePath}/short-video/account/by-file`;
18462
18573
  const response = await this.http.post(url2, {
18463
18574
  ...data,
18464
- createdFrom: "npmPackage"
18575
+ createdFrom: this.http.createdFrom
18465
18576
  });
18466
18577
  return response.result?._id;
18467
18578
  }
@@ -18474,7 +18585,7 @@ var SocialPublisherPostClient = class {
18474
18585
  const url2 = id ? `${this.basePath}/short-video/account/by-url/${id}` : `${this.basePath}/short-video/account/by-url`;
18475
18586
  const response = await this.http.post(url2, {
18476
18587
  ...data,
18477
- createdFrom: "npmPackage"
18588
+ createdFrom: this.http.createdFrom
18478
18589
  });
18479
18590
  return response.result?._id;
18480
18591
  }
@@ -18498,7 +18609,7 @@ var SocialPublisherPostClient = class {
18498
18609
  const url2 = id ? `${this.basePath}/image/workspace/${id}` : `${this.basePath}/image/workspace`;
18499
18610
  const response = await this.http.post(url2, {
18500
18611
  ...data,
18501
- createdFrom: "npmPackage"
18612
+ createdFrom: this.http.createdFrom
18502
18613
  });
18503
18614
  return response.result?._id;
18504
18615
  }
@@ -18511,10 +18622,50 @@ var SocialPublisherPostClient = class {
18511
18622
  const url2 = id ? `${this.basePath}/image/account/${id}` : `${this.basePath}/image/account`;
18512
18623
  const response = await this.http.post(url2, {
18513
18624
  ...data,
18514
- createdFrom: "npmPackage"
18625
+ createdFrom: this.http.createdFrom
18515
18626
  });
18516
18627
  return response.result?._id;
18517
18628
  }
18629
+ /**
18630
+ * Publish a text-only post to every text-capable account in a workspace
18631
+ * (Facebook, Threads, X). Platforms that cannot take text are reported in
18632
+ * `skippedPlatforms`; X below the Pro plan is dropped into `refusedTargets`.
18633
+ */
18634
+ async createTextPostToWorkspace(data) {
18635
+ const response = await this.http.post(`${this.basePath}/text/workspace`, {
18636
+ ...data,
18637
+ createdFrom: this.http.createdFrom
18638
+ });
18639
+ return response.result;
18640
+ }
18641
+ /** Publish a text-only post to one account. */
18642
+ async createTextPostToAccount(data) {
18643
+ const response = await this.http.post(`${this.basePath}/text/account`, {
18644
+ ...data,
18645
+ createdFrom: this.http.createdFrom
18646
+ });
18647
+ return response.result;
18648
+ }
18649
+ /**
18650
+ * Publish a story to every story-capable account in a workspace. Media by URL
18651
+ * only in this release: `image: { source: "image-url", externalUrl }`, or
18652
+ * `source: "video-url"` with `videoURL`.
18653
+ */
18654
+ async createStoryPostToWorkspace(data) {
18655
+ const response = await this.http.post(`${this.basePath}/story/workspace`, {
18656
+ ...data,
18657
+ createdFrom: this.http.createdFrom
18658
+ });
18659
+ return response.result;
18660
+ }
18661
+ /** Publish a story to one account. Media by URL only, as for the workspace form. */
18662
+ async createStoryPostToAccount(data) {
18663
+ const response = await this.http.post(`${this.basePath}/story/account`, {
18664
+ ...data,
18665
+ createdFrom: this.http.createdFrom
18666
+ });
18667
+ return response.result;
18668
+ }
18518
18669
  /**
18519
18670
  * Handle thumbnail upload - accepts either File or URL string
18520
18671
  * @param thumb - Thumbnail as File (will be uploaded) or URL string (will be passed directly)
@@ -18862,7 +19013,7 @@ var SocialPublisherPostClient = class {
18862
19013
  const target = isFile2 ? "by-file" : "by-url";
18863
19014
  const id = postId ?? thumb?.postId;
18864
19015
  const url2 = id ? `${this.basePath}/long-video/workspace/${target}/${id}` : `${this.basePath}/long-video/workspace/${target}`;
18865
- const response = await this.http.post(url2, { ...body, createdFrom: "npmPackage" });
19016
+ const response = await this.http.post(url2, { ...body, createdFrom: this.http.createdFrom });
18866
19017
  return this.normaliseLongVideoResult(response.result);
18867
19018
  }
18868
19019
  /**
@@ -18914,7 +19065,7 @@ var SocialPublisherPostClient = class {
18914
19065
  const target = isFile2 ? "by-file" : "by-url";
18915
19066
  const id = postId ?? thumb?.postId;
18916
19067
  const url2 = id ? `${this.basePath}/long-video/account/${target}/${id}` : `${this.basePath}/long-video/account/${target}`;
18917
- const response = await this.http.post(url2, { ...body, createdFrom: "npmPackage" });
19068
+ const response = await this.http.post(url2, { ...body, createdFrom: this.http.createdFrom });
18918
19069
  return this.normaliseLongVideoResult(response.result);
18919
19070
  }
18920
19071
  /**
@@ -18926,18 +19077,29 @@ var SocialPublisherPostClient = class {
18926
19077
  *
18927
19078
  * @example
18928
19079
  * ```ts
18929
- * await client.reschedulePost("post_123", { schedule: new Date("2026-09-01T09:00:00Z") });
18930
- * await client.reschedulePost("post_123", { schedule: "now" });
19080
+ * const post = await client.getStatus("post_123");
19081
+ * const { __v } = await client.reschedulePost("post_123", { schedule: new Date("2026-09-01T09:00:00Z") }, post.__v);
19082
+ * await client.reschedulePost("post_123", { schedule: "now" }, __v);
18931
19083
  * ```
19084
+ *
19085
+ * @param version - The post's `__v` as you read it. A stale one throws `ConflictError`.
19086
+ * @returns `{ _id, __v }`, `__v` being the new version
18932
19087
  */
18933
- async reschedulePost(id, data) {
19088
+ async reschedulePost(id, data, version) {
18934
19089
  if (!id) {
18935
19090
  throw new Error("id is required");
18936
19091
  }
18937
- await this.http.put(`${this.basePath}/${id}`, {
18938
- schedule: this.buildSchedule(data.schedule),
18939
- ...data.caption !== void 0 ? { caption: data.caption } : {}
18940
- });
19092
+ assertVersion(version);
19093
+ const response = await this.http.put(
19094
+ `${this.basePath}/${id}`,
19095
+ {
19096
+ ...data.schedule === "now" ? { scheduleType: "now" } : { scheduleType: "schedule", scheduledAt: data.schedule.toISOString() },
19097
+ ...data.caption !== void 0 ? { caption: data.caption } : {}
19098
+ },
19099
+ { version }
19100
+ );
19101
+ const updated = withVersion(response, id);
19102
+ return { _id: updated._id, __v: updated.__v };
18941
19103
  }
18942
19104
  /**
18943
19105
  * Delete a post that has not published yet, releasing its uploaded media in
@@ -18949,14 +19111,17 @@ var SocialPublisherPostClient = class {
18949
19111
  *
18950
19112
  * @example
18951
19113
  * ```ts
18952
- * await client.deletePost("post_123");
19114
+ * await client.deletePost("post_123", post.__v);
18953
19115
  * ```
19116
+ *
19117
+ * @param version - The post's `__v` as you read it. A stale one throws `ConflictError`.
18954
19118
  */
18955
- async deletePost(id) {
19119
+ async deletePost(id, version) {
18956
19120
  if (!id) {
18957
19121
  throw new Error("id is required");
18958
19122
  }
18959
- await this.http.delete(`${this.basePath}/${id}`);
19123
+ assertVersion(version);
19124
+ await this.http.delete(`${this.basePath}/${id}`, { version });
18960
19125
  }
18961
19126
  /**
18962
19127
  * Upload a long video and return the URL to publish from.