@scalemule/sdk 0.0.54 → 0.0.56

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.mjs CHANGED
@@ -1960,6 +1960,24 @@ var DEFAULT_STALL_TIMEOUT_MS = 45e3;
1960
1960
  var SLOW_NETWORK_STALL_TIMEOUT_MS = 9e4;
1961
1961
  var MULTIPART_THRESHOLD = 8 * 1024 * 1024;
1962
1962
  var MULTIPART_THRESHOLD_SLOW = 4 * 1024 * 1024;
1963
+ function buildVisibilityWire(options) {
1964
+ if (!options) return {};
1965
+ if (options.visibility) {
1966
+ return {
1967
+ visibility: options.visibility,
1968
+ // Legacy field for old storage instances that haven't deployed
1969
+ // the tristate handler yet — omit `is_public` for the
1970
+ // `anonymous_visible` case so an old server that doesn't know
1971
+ // the new value at least falls through to its own default
1972
+ // rather than mis-treating it as `app_public`.
1973
+ ...options.visibility === "private" ? { is_public: false } : options.visibility === "app_public" ? { is_public: true } : {}
1974
+ };
1975
+ }
1976
+ if (typeof options.isPublic === "boolean") {
1977
+ return { is_public: options.isPublic };
1978
+ }
1979
+ return {};
1980
+ }
1963
1981
  var StorageService = class extends ServiceModule {
1964
1982
  constructor() {
1965
1983
  super(...arguments);
@@ -2041,6 +2059,42 @@ var StorageService = class extends ServiceModule {
2041
2059
  }
2042
2060
  return result;
2043
2061
  }
2062
+ /**
2063
+ * Upload a file as world-readable on the anonymous public CDN.
2064
+ *
2065
+ * Same browser→S3 pipeline as {@link upload}, but pins
2066
+ * `visibility: 'anonymous_visible'` — caller cannot opt out.
2067
+ *
2068
+ * Use this for media meant to render on logged-out marketing
2069
+ * pages, blog posts, embed snippets — anywhere a customer needs
2070
+ * to drop a URL into `<img src>` without an authenticated
2071
+ * session. For everything else (chat attachments, private
2072
+ * uploads, app-internal galleries) prefer {@link upload} or
2073
+ * {@link uploadPrivate}.
2074
+ *
2075
+ * **`cdn_url` may be `null` on the immediate response.** Storage
2076
+ * intentionally withholds the public CDN URL until the AV scan
2077
+ * has flipped to `clean` — exposing the URL pre-scan would let a
2078
+ * customer embed the bytes in a logged-out page before the
2079
+ * platform has verified them. The upload itself succeeds
2080
+ * regardless; consumers should check `result.data.cdn_url` and:
2081
+ * - if non-null → it's safe to publish
2082
+ * - if null → poll {@link getFileStatus} on a small backoff
2083
+ * until `urls.cdn_url` populates (or `scan.status` flips to
2084
+ * `threat` / `quarantined` / `error` — terminal failure)
2085
+ *
2086
+ * Requires the operator to have provisioned the anonymous
2087
+ * delivery bucket + CDN. When they haven't, the storage service
2088
+ * returns 503 `ANONYMOUS_DELIVERY_NOT_CONFIGURED` (an error
2089
+ * propagated through this helper) — it never silently demotes
2090
+ * to `app_public`.
2091
+ */
2092
+ async uploadAnonymous(file, options) {
2093
+ return this.upload(file, {
2094
+ ...options,
2095
+ visibility: "anonymous_visible"
2096
+ });
2097
+ }
2044
2098
  // --------------------------------------------------------------------------
2045
2099
  // Direct Upload (3-step with retry + stall)
2046
2100
  // --------------------------------------------------------------------------
@@ -2054,7 +2108,7 @@ var StorageService = class extends ServiceModule {
2054
2108
  filename,
2055
2109
  content_type: file.type || "application/octet-stream",
2056
2110
  size_bytes: file.size,
2057
- is_public: options?.isPublic ?? true,
2111
+ ...buildVisibilityWire(options),
2058
2112
  metadata: options?.metadata
2059
2113
  },
2060
2114
  requestOpts
@@ -2145,6 +2199,13 @@ var StorageService = class extends ServiceModule {
2145
2199
  content_type: d.content_type,
2146
2200
  size_bytes: d.size_bytes,
2147
2201
  url: d.url,
2202
+ // Surface visibility + cdn_url all the way out so callers
2203
+ // can branch on visibility without a follow-up getInfo()
2204
+ // round-trip. Anonymous-visible callers especially need
2205
+ // `cdn_url` here to render the image immediately.
2206
+ visibility: d.visibility,
2207
+ cdn_url: d.cdn_url,
2208
+ is_public: d.visibility ? d.visibility !== "private" : void 0,
2148
2209
  created_at: (/* @__PURE__ */ new Date()).toISOString()
2149
2210
  },
2150
2211
  error: null
@@ -2226,7 +2287,7 @@ var StorageService = class extends ServiceModule {
2226
2287
  filename,
2227
2288
  content_type: file.type || "application/octet-stream",
2228
2289
  size_bytes: file.size,
2229
- is_public: options?.isPublic ?? true,
2290
+ ...buildVisibilityWire(options),
2230
2291
  metadata: options?.metadata,
2231
2292
  chunk_size: options?.chunkSize,
2232
2293
  ...clientUploadKey ? { client_upload_key: clientUploadKey } : {}
@@ -2504,6 +2565,9 @@ var StorageService = class extends ServiceModule {
2504
2565
  content_type: d.content_type,
2505
2566
  size_bytes: d.size_bytes,
2506
2567
  url: d.url,
2568
+ visibility: d.visibility,
2569
+ cdn_url: d.cdn_url,
2570
+ is_public: d.visibility ? d.visibility !== "private" : void 0,
2507
2571
  created_at: (/* @__PURE__ */ new Date()).toISOString()
2508
2572
  },
2509
2573
  error: null
@@ -2541,7 +2605,7 @@ var StorageService = class extends ServiceModule {
2541
2605
  {
2542
2606
  filename,
2543
2607
  content_type: contentType,
2544
- is_public: options?.isPublic ?? true,
2608
+ ...buildVisibilityWire(options),
2545
2609
  expires_in: options?.expiresIn ?? 3600,
2546
2610
  size_bytes: options?.sizeBytes,
2547
2611
  metadata: options?.metadata
@@ -2588,7 +2652,16 @@ var StorageService = class extends ServiceModule {
2588
2652
  // --------------------------------------------------------------------------
2589
2653
  // Multipart Public API (for advanced/server-side usage)
2590
2654
  // --------------------------------------------------------------------------
2591
- /** Start a multipart upload session. */
2655
+ /**
2656
+ * Start a multipart upload session.
2657
+ *
2658
+ * Accepts both the typed `visibility` field (preferred) and the
2659
+ * legacy `is_public` boolean for back-compat. If both are sent the
2660
+ * storage service uses `visibility`. `'anonymous_visible'` requires
2661
+ * the operator to have provisioned the anonymous bucket — the
2662
+ * service returns 503 `ANONYMOUS_DELIVERY_NOT_CONFIGURED`
2663
+ * otherwise (the SDK never silently demotes).
2664
+ */
2592
2665
  async startMultipartUpload(params, requestOptions) {
2593
2666
  return this.post("/signed-url/multipart/start", params, requestOptions);
2594
2667
  }
@@ -2719,14 +2792,26 @@ var StorageService = class extends ServiceModule {
2719
2792
  return this._get(`/files/${fileId}/view-status`, options);
2720
2793
  }
2721
2794
  /**
2722
- * Update a file's visibility (public/private).
2723
- * Only the file owner can toggle this. Changes URL TTL — does not move the S3 object.
2724
- * Public files get 7-day signed URLs; private files get 1-hour signed URLs.
2795
+ * Update a file's visibility.
2796
+ *
2797
+ * Accepts either:
2798
+ * - a tri-state {@link Visibility} string (preferred), or
2799
+ * - a legacy boolean (`true` → `app_public`, `false` → `private`).
2800
+ *
2801
+ * Only the file owner / app member can toggle this. Same-bucket
2802
+ * transitions (`private` ↔ `app_public`) succeed and the service
2803
+ * keeps the legacy `is_public` column in sync via a DB trigger.
2804
+ * Cross-bucket transitions (any flip into or out of
2805
+ * `'anonymous_visible'`) currently return 409
2806
+ * `VISIBILITY_TRANSITION_UNSUPPORTED` — the bytes would need to
2807
+ * move between S3 buckets and that orchestration is not yet
2808
+ * shipped. Re-upload the file with the desired visibility instead.
2725
2809
  */
2726
- async updateVisibility(fileId, isPublic, options) {
2810
+ async updateVisibility(fileId, visibility, options) {
2811
+ const body = typeof visibility === "boolean" ? { is_public: visibility } : { visibility };
2727
2812
  return this.patch(
2728
2813
  `/files/${fileId}/visibility`,
2729
- { is_public: isPublic },
2814
+ body,
2730
2815
  options
2731
2816
  );
2732
2817
  }
@@ -6122,6 +6207,41 @@ var PhotoService = class extends ServiceModule {
6122
6207
  const qs = params.toString();
6123
6208
  return `${this.client.getBaseUrl()}${this.basePath}/${photoId}/transform${qs ? `?${qs}` : ""}`;
6124
6209
  }
6210
+ /**
6211
+ * Build an absolute URL for the **public** transform endpoint —
6212
+ * the unauthenticated path that serves transformed bytes for
6213
+ * `<img src>` use on logged-out marketing pages, blogs, embeds.
6214
+ *
6215
+ * The photo service refuses any photo that isn't:
6216
+ * - `visibility = 'anonymous_visible'` (the customer explicitly
6217
+ * opted into world-readable for this file at upload time)
6218
+ * - `scan_status = 'clean'` (no exception for pending/scanning)
6219
+ *
6220
+ * Anything else returns 404 — the endpoint refuses to disambiguate
6221
+ * "not found" from "not anonymous" so it can't be probed to
6222
+ * discover existence or visibility of private photos.
6223
+ *
6224
+ * Pair with {@link getTransformUrl} for the authenticated case:
6225
+ * customer apps that already have a session should keep using the
6226
+ * authed transform URL (which also handles `anonymous_visible`
6227
+ * photos transparently) — this URL is for cross-origin embedding.
6228
+ *
6229
+ * @example
6230
+ * ```tsx
6231
+ * // photo was uploaded with visibility: 'anonymous_visible'
6232
+ * <img src={sm.photo.getPublicTransformUrl(photoId, { width: 800 })} />
6233
+ * ```
6234
+ */
6235
+ getPublicTransformUrl(photoId, options) {
6236
+ const params = new URLSearchParams();
6237
+ if (options?.width) params.set("width", String(options.width));
6238
+ if (options?.height) params.set("height", String(options.height));
6239
+ if (options?.fit) params.set("fit", options.fit);
6240
+ if (options?.format) params.set("format", options.format);
6241
+ if (options?.quality) params.set("quality", String(options.quality));
6242
+ const qs = params.toString();
6243
+ return `${this.client.getBaseUrl()}${this.basePath}/public/${photoId}/transform${qs ? `?${qs}` : ""}`;
6244
+ }
6125
6245
  /**
6126
6246
  * Get a transform URL optimized for the given display area.
6127
6247
  *
@@ -6319,6 +6439,565 @@ var PhotoService = class extends ServiceModule {
6319
6439
  }
6320
6440
  };
6321
6441
 
6442
+ // src/services/media.ts
6443
+ var MEDIA_PRESETS = {
6444
+ hero: { widths: [400, 800, 1200, 1600, 2400] },
6445
+ inline: { widths: [400, 800, 1200] },
6446
+ thumbnail: { widths: [120, 240, 360], fit: "cover" },
6447
+ avatar: { widths: [64, 128, 256], fit: "cover" },
6448
+ logo: { widths: [120, 240, 480] }
6449
+ };
6450
+ var MediaService = class extends ServiceModule {
6451
+ constructor(client, storage, photo, video, audio) {
6452
+ super(client);
6453
+ this.storage = storage;
6454
+ this.photo = photo;
6455
+ this.video = video;
6456
+ this.audio = audio;
6457
+ this.basePath = "";
6458
+ }
6459
+ getPresets() {
6460
+ return MEDIA_PRESETS;
6461
+ }
6462
+ async upload(file, options, requestOptions) {
6463
+ const mimeType = file.type || "application/octet-stream";
6464
+ const kind = detectKind(mimeType);
6465
+ const visibility = resolveVisibility(options);
6466
+ const isPublic = visibility !== "private";
6467
+ const isAnonymous = visibility === "anonymous_visible";
6468
+ const gateOnPipeline = shouldGateOnPipeline(options?.policy);
6469
+ const emit = (phase, progress, fileId) => {
6470
+ options?.onProgress?.({ phase, progress, file_id: fileId });
6471
+ };
6472
+ const uploadOptions = {
6473
+ filename: options?.filename,
6474
+ metadata: options?.metadata,
6475
+ signal: options?.signal,
6476
+ onProgress: (progress) => emit("uploading", progress)
6477
+ };
6478
+ emit("presigning", 0);
6479
+ try {
6480
+ if (isAnonymous) {
6481
+ return await this.uploadAnonymous(file, mimeType, kind, options, requestOptions, uploadOptions, emit);
6482
+ }
6483
+ if (kind === "image" && !options?.skipPhotoRegister) {
6484
+ return await this.uploadImage(
6485
+ file,
6486
+ mimeType,
6487
+ visibility,
6488
+ gateOnPipeline,
6489
+ options,
6490
+ requestOptions,
6491
+ uploadOptions,
6492
+ emit
6493
+ );
6494
+ }
6495
+ if (kind === "video" && visibility === "private") {
6496
+ const result = await this.video.uploadViaStorage(file, uploadOptions, requestOptions);
6497
+ if (result.error || !result.data) {
6498
+ return { data: null, error: result.error };
6499
+ }
6500
+ if (gateOnPipeline) {
6501
+ emit("optimizing", 100, result.data.file_id);
6502
+ await result.data.hls_url_promise;
6503
+ }
6504
+ const info = await this.fetchInfoBestEffort(result.data.file_id, requestOptions);
6505
+ const asset2 = this.buildAsset(
6506
+ info ?? fallbackFileInfo(result.data.file_id, mimeType, visibility, result.data.original_view_url, null),
6507
+ {
6508
+ photoId: null,
6509
+ preset: options?.preset,
6510
+ customWidths: options?.customWidths
6511
+ }
6512
+ );
6513
+ emit("ready", 100, result.data.file_id);
6514
+ return {
6515
+ data: {
6516
+ file_id: result.data.file_id,
6517
+ photo_id: null,
6518
+ original_view_url: result.data.original_view_url,
6519
+ optimized_url_promise: Promise.resolve(null),
6520
+ hls_url_promise: result.data.hls_url_promise,
6521
+ mime_type: mimeType,
6522
+ is_public: false,
6523
+ visibility,
6524
+ cdn_url: null,
6525
+ asset: asset2
6526
+ },
6527
+ error: null
6528
+ };
6529
+ }
6530
+ if (kind === "audio" && visibility === "private") {
6531
+ const result = await this.audio.uploadViaStorage(file, uploadOptions, requestOptions);
6532
+ if (result.error || !result.data) {
6533
+ return { data: null, error: result.error };
6534
+ }
6535
+ const info = await this.fetchInfoBestEffort(result.data.file_id, requestOptions);
6536
+ const asset2 = this.buildAsset(
6537
+ info ?? fallbackFileInfo(result.data.file_id, mimeType, visibility, result.data.original_view_url, null),
6538
+ {
6539
+ photoId: null,
6540
+ preset: options?.preset,
6541
+ customWidths: options?.customWidths
6542
+ }
6543
+ );
6544
+ emit("ready", 100, result.data.file_id);
6545
+ return {
6546
+ data: {
6547
+ file_id: result.data.file_id,
6548
+ photo_id: null,
6549
+ original_view_url: result.data.original_view_url,
6550
+ optimized_url_promise: Promise.resolve(null),
6551
+ hls_url_promise: Promise.resolve(null),
6552
+ mime_type: mimeType,
6553
+ is_public: false,
6554
+ visibility,
6555
+ cdn_url: null,
6556
+ asset: asset2
6557
+ },
6558
+ error: null
6559
+ };
6560
+ }
6561
+ const storageResult = isPublic ? await this.storage.upload(file, {
6562
+ ...uploadOptions,
6563
+ visibility: "app_public",
6564
+ skipCompression: true
6565
+ }) : await this.storage.uploadPrivate(file, uploadOptions);
6566
+ if (storageResult.error || !storageResult.data) {
6567
+ return { data: null, error: storageResult.error };
6568
+ }
6569
+ const fileInfo = storageResult.data;
6570
+ const asset = this.buildAsset(fileInfo, {
6571
+ photoId: null,
6572
+ preset: options?.preset,
6573
+ customWidths: options?.customWidths
6574
+ });
6575
+ emit("ready", 100, fileInfo.id);
6576
+ return {
6577
+ data: {
6578
+ file_id: fileInfo.id,
6579
+ photo_id: null,
6580
+ original_view_url: fileInfo.url ?? null,
6581
+ optimized_url_promise: Promise.resolve(null),
6582
+ hls_url_promise: Promise.resolve(null),
6583
+ mime_type: mimeType,
6584
+ is_public: fileInfo.is_public ?? isPublic,
6585
+ visibility: resolveFileVisibility(fileInfo, visibility),
6586
+ cdn_url: fileInfo.cdn_url ?? null,
6587
+ asset
6588
+ },
6589
+ error: null
6590
+ };
6591
+ } catch (error) {
6592
+ return {
6593
+ data: null,
6594
+ error: normalizeThrownError(error)
6595
+ };
6596
+ }
6597
+ }
6598
+ async get(fileId, options, requestOptions) {
6599
+ const result = await this.storage.getInfo(fileId, requestOptions);
6600
+ if (result.error || !result.data) {
6601
+ return { data: null, error: result.error };
6602
+ }
6603
+ return {
6604
+ data: this.buildAsset(result.data, {
6605
+ photoId: null,
6606
+ preset: options?.preset,
6607
+ customWidths: options?.customWidths
6608
+ }),
6609
+ error: null
6610
+ };
6611
+ }
6612
+ async list(params, requestOptions) {
6613
+ const result = await this.storage.list(params, requestOptions);
6614
+ return {
6615
+ data: result.data.map(
6616
+ (file) => this.buildAsset(file, {
6617
+ photoId: null,
6618
+ preset: params?.preset,
6619
+ customWidths: params?.customWidths
6620
+ })
6621
+ ),
6622
+ metadata: result.metadata,
6623
+ error: result.error
6624
+ };
6625
+ }
6626
+ async delete(fileId, options) {
6627
+ try {
6628
+ const [, storageResult] = await Promise.all([
6629
+ this.photo.delete(fileId, options).catch(() => ({ data: null, error: null })),
6630
+ this.storage.delete(fileId, options)
6631
+ ]);
6632
+ if (storageResult.error && storageResult.error.status !== 404) {
6633
+ return { data: null, error: storageResult.error };
6634
+ }
6635
+ return { data: { deleted: true }, error: null };
6636
+ } catch (error) {
6637
+ return { data: null, error: normalizeThrownError(error) };
6638
+ }
6639
+ }
6640
+ async releaseQuarantine(fileId, reason = "Released via @scalemule/sdk media.releaseQuarantine()", options) {
6641
+ const response = await this.client.post(
6642
+ `/v1/storage/admin/files/${fileId}/scan-override`,
6643
+ { scan_status: "clean", reason },
6644
+ options
6645
+ );
6646
+ if (response.error) {
6647
+ return { data: null, error: response.error };
6648
+ }
6649
+ return this.get(fileId, void 0, options);
6650
+ }
6651
+ async getManifest(fileId, options, requestOptions) {
6652
+ const asset = await this.get(fileId, options, requestOptions);
6653
+ if (asset.error || !asset.data) {
6654
+ return { data: null, error: asset.error };
6655
+ }
6656
+ return { data: asset.data.manifest, error: null };
6657
+ }
6658
+ buildAsset(file, options) {
6659
+ const visibility = resolveFileVisibility(file);
6660
+ const photoId = options?.photoId ?? null;
6661
+ const originalUrl = visibility === "anonymous_visible" ? file.cdn_url ?? file.url ?? null : file.url ?? file.cdn_url ?? null;
6662
+ return {
6663
+ file_id: file.id,
6664
+ photo_id: photoId,
6665
+ filename: file.filename,
6666
+ content_type: file.content_type,
6667
+ size_bytes: file.size_bytes,
6668
+ kind: detectKind(file.content_type),
6669
+ visibility,
6670
+ is_public: file.is_public ?? visibility !== "private",
6671
+ scan_status: file.scan_status,
6672
+ created_at: file.created_at,
6673
+ original_url: originalUrl,
6674
+ cdn_url: file.cdn_url ?? null,
6675
+ manifest: this.buildManifest(file, options)
6676
+ };
6677
+ }
6678
+ buildManifest(file, options) {
6679
+ const kind = detectKind(file.content_type);
6680
+ const visibility = resolveFileVisibility(file);
6681
+ const originalUrl = visibility === "anonymous_visible" ? file.cdn_url ?? file.url ?? null : file.url ?? file.cdn_url ?? null;
6682
+ if (!originalUrl) {
6683
+ return null;
6684
+ }
6685
+ if (kind !== "image" || file.content_type === "image/svg+xml") {
6686
+ return {
6687
+ file_id: file.id,
6688
+ content_type: file.content_type,
6689
+ preset: "original",
6690
+ variants: { original: originalUrl },
6691
+ srcset: null,
6692
+ default: originalUrl
6693
+ };
6694
+ }
6695
+ const preset = options?.preset ?? "inline";
6696
+ const spec = resolvePresetSpec(preset, options?.customWidths);
6697
+ const variants = Object.fromEntries(
6698
+ spec.widths.map((width) => [
6699
+ String(width),
6700
+ visibility === "anonymous_visible" ? this.photo.getPublicTransformUrl(file.id, transformOptions(width, spec.fit)) : this.photo.getTransformUrl(file.id, transformOptions(width, spec.fit))
6701
+ ])
6702
+ );
6703
+ const defaultWidth = pickDefaultWidth(spec.widths);
6704
+ const defaultUrl = variants[String(defaultWidth)] ?? Object.values(variants)[0] ?? originalUrl;
6705
+ return {
6706
+ file_id: file.id,
6707
+ content_type: file.content_type,
6708
+ preset,
6709
+ variants,
6710
+ srcset: spec.widths.map((width) => `${variants[String(width)]} ${width}w`).join(", "),
6711
+ default: defaultUrl
6712
+ };
6713
+ }
6714
+ async uploadAnonymous(file, mimeType, kind, options, requestOptions, uploadOptions, emit) {
6715
+ const result = await this.storage.uploadAnonymous(file, uploadOptions);
6716
+ if (result.error || !result.data) {
6717
+ return { data: null, error: result.error };
6718
+ }
6719
+ emit("scanning", 100, result.data.id);
6720
+ const ready = await this.waitForAnonymousReady(result.data.id, options?.signal, emit);
6721
+ if (ready.error) {
6722
+ return { data: null, error: ready.error };
6723
+ }
6724
+ const fileInfo = await this.fetchInfoBestEffort(result.data.id, requestOptions) ?? {
6725
+ ...result.data,
6726
+ cdn_url: ready.cdnUrl ?? result.data.cdn_url,
6727
+ scan_status: ready.scanStatus
6728
+ };
6729
+ const manifest = this.buildManifest(fileInfo, {
6730
+ preset: options?.preset,
6731
+ customWidths: options?.customWidths
6732
+ });
6733
+ if (kind === "image" && fileInfo.content_type !== "image/svg+xml" && options?.prewarm !== false) {
6734
+ emit("optimizing", 100, result.data.id);
6735
+ await this.prewarmManifest(manifest, options?.signal);
6736
+ }
6737
+ const asset = this.buildAsset(fileInfo, {
6738
+ photoId: null,
6739
+ preset: options?.preset,
6740
+ customWidths: options?.customWidths
6741
+ });
6742
+ emit("ready", 100, result.data.id);
6743
+ return {
6744
+ data: {
6745
+ file_id: result.data.id,
6746
+ photo_id: null,
6747
+ original_view_url: fileInfo.cdn_url ?? null,
6748
+ optimized_url_promise: Promise.resolve(manifest?.default ?? null),
6749
+ hls_url_promise: Promise.resolve(null),
6750
+ mime_type: mimeType,
6751
+ is_public: true,
6752
+ visibility: "anonymous_visible",
6753
+ cdn_url: fileInfo.cdn_url ?? null,
6754
+ asset
6755
+ },
6756
+ error: null
6757
+ };
6758
+ }
6759
+ async uploadImage(file, mimeType, visibility, gateOnPipeline, options, requestOptions, uploadOptions, emit) {
6760
+ if (visibility === "private") {
6761
+ const result = await this.photo.uploadViaStorage(file, uploadOptions, requestOptions);
6762
+ if (result.error || !result.data) {
6763
+ return { data: null, error: result.error };
6764
+ }
6765
+ if (gateOnPipeline) {
6766
+ emit("optimizing", 100, result.data.file_id);
6767
+ await result.data.optimized_url_promise;
6768
+ }
6769
+ const info2 = await this.fetchInfoBestEffort(result.data.file_id, requestOptions);
6770
+ const asset2 = this.buildAsset(
6771
+ info2 ?? fallbackFileInfo(result.data.file_id, mimeType, visibility, result.data.original_view_url, null),
6772
+ {
6773
+ photoId: result.data.photo_id,
6774
+ preset: options?.preset,
6775
+ customWidths: options?.customWidths
6776
+ }
6777
+ );
6778
+ emit("ready", 100, result.data.file_id);
6779
+ return {
6780
+ data: {
6781
+ file_id: result.data.file_id,
6782
+ photo_id: result.data.photo_id,
6783
+ original_view_url: result.data.original_view_url,
6784
+ optimized_url_promise: result.data.optimized_url_promise,
6785
+ hls_url_promise: Promise.resolve(null),
6786
+ mime_type: mimeType,
6787
+ is_public: false,
6788
+ visibility,
6789
+ cdn_url: null,
6790
+ asset: asset2
6791
+ },
6792
+ error: null
6793
+ };
6794
+ }
6795
+ const storageResult = await this.storage.upload(file, {
6796
+ ...uploadOptions,
6797
+ visibility: "app_public",
6798
+ skipCompression: true
6799
+ });
6800
+ if (storageResult.error || !storageResult.data) {
6801
+ return { data: null, error: storageResult.error };
6802
+ }
6803
+ const originalViewUrl = storageResult.data.url ?? null;
6804
+ const registerResult = await this.photo.register({ fileId: storageResult.data.id }, requestOptions);
6805
+ const photoId = registerResult.error || !registerResult.data ? null : registerResult.data.id;
6806
+ const optimizedUrlPromise = photoId ? this.pollPhotoOptimizationComplete(photoId, requestOptions) : Promise.resolve(null);
6807
+ if (gateOnPipeline) {
6808
+ emit("optimizing", 100, storageResult.data.id);
6809
+ await optimizedUrlPromise;
6810
+ }
6811
+ const info = await this.fetchInfoBestEffort(storageResult.data.id, requestOptions) ?? storageResult.data;
6812
+ const asset = this.buildAsset(info, {
6813
+ photoId,
6814
+ preset: options?.preset,
6815
+ customWidths: options?.customWidths
6816
+ });
6817
+ emit("ready", 100, storageResult.data.id);
6818
+ return {
6819
+ data: {
6820
+ file_id: storageResult.data.id,
6821
+ photo_id: photoId,
6822
+ original_view_url: originalViewUrl,
6823
+ optimized_url_promise: optimizedUrlPromise,
6824
+ hls_url_promise: Promise.resolve(null),
6825
+ mime_type: mimeType,
6826
+ is_public: true,
6827
+ visibility,
6828
+ cdn_url: info.cdn_url ?? null,
6829
+ asset
6830
+ },
6831
+ error: null
6832
+ };
6833
+ }
6834
+ async waitForAnonymousReady(fileId, signal, emit) {
6835
+ const delays = [500, 1e3, 1500, 2e3, 2500, 3e3];
6836
+ for (let attempt = 0; attempt < 24; attempt++) {
6837
+ if (signal?.aborted) {
6838
+ return {
6839
+ cdnUrl: null,
6840
+ scanStatus: void 0,
6841
+ error: { code: "aborted", message: "Upload aborted", status: 0 }
6842
+ };
6843
+ }
6844
+ const status = await this.storage.getFileStatus(fileId);
6845
+ if (status.error || !status.data) {
6846
+ await sleep4(delays[Math.min(attempt, delays.length - 1)] ?? 3e3);
6847
+ continue;
6848
+ }
6849
+ const scanStatus = status.data.scan.status;
6850
+ if (status.data.urls.cdn_url) {
6851
+ return { cdnUrl: status.data.urls.cdn_url, scanStatus, error: null };
6852
+ }
6853
+ if (scanStatus === "threat" || scanStatus === "quarantined" || scanStatus === "error") {
6854
+ return {
6855
+ cdnUrl: null,
6856
+ scanStatus,
6857
+ error: scanError(scanStatus)
6858
+ };
6859
+ }
6860
+ emit("scanning", Math.min(99, 10 + attempt * 4), fileId);
6861
+ await sleep4(delays[Math.min(attempt, delays.length - 1)] ?? 3e3);
6862
+ }
6863
+ return {
6864
+ cdnUrl: null,
6865
+ scanStatus: "pending",
6866
+ error: {
6867
+ code: "file_scanning",
6868
+ message: "File scan did not complete in time. Re-fetch the file status and publish once cdn_url appears.",
6869
+ status: 202
6870
+ }
6871
+ };
6872
+ }
6873
+ async fetchInfoBestEffort(fileId, requestOptions) {
6874
+ const result = await this.storage.getInfo(fileId, requestOptions);
6875
+ return result.error || !result.data ? null : result.data;
6876
+ }
6877
+ async pollPhotoOptimizationComplete(photoId, requestOptions) {
6878
+ for (let attempt = 0; attempt < 40; attempt++) {
6879
+ const result = await this.photo.get(photoId, requestOptions);
6880
+ const status = result.data?.optimization_status;
6881
+ if (status === "completed") {
6882
+ return this.photo.getTransformUrl(photoId, { width: 1200 });
6883
+ }
6884
+ await sleep4(250);
6885
+ }
6886
+ return null;
6887
+ }
6888
+ async prewarmManifest(manifest, signal) {
6889
+ if (!manifest || manifest.preset === "original") {
6890
+ return;
6891
+ }
6892
+ const urls = Object.values(manifest.variants);
6893
+ await Promise.all(
6894
+ urls.map(async (url) => {
6895
+ try {
6896
+ const response = await fetch(url, {
6897
+ method: "GET",
6898
+ signal,
6899
+ headers: {
6900
+ Accept: "image/avif,image/webp,image/*,*/*;q=0.8"
6901
+ }
6902
+ });
6903
+ if (!response.ok) {
6904
+ throw new Error(`Prewarm failed with HTTP ${response.status}`);
6905
+ }
6906
+ await response.arrayBuffer();
6907
+ } catch (error) {
6908
+ console.warn("[scalemule-sdk] media prewarm failed", url, error);
6909
+ }
6910
+ })
6911
+ );
6912
+ }
6913
+ };
6914
+ function detectKind(contentType) {
6915
+ if (contentType.startsWith("image/")) return "image";
6916
+ if (contentType.startsWith("video/")) return "video";
6917
+ if (contentType.startsWith("audio/")) return "audio";
6918
+ if (contentType.includes("pdf") || contentType.includes("text/") || contentType.includes("word") || contentType.includes("sheet") || contentType.includes("presentation")) {
6919
+ return "document";
6920
+ }
6921
+ return "other";
6922
+ }
6923
+ function resolveVisibility(options) {
6924
+ if (options?.visibility) return options.visibility;
6925
+ if (options?.isPublic === true) return "app_public";
6926
+ return "private";
6927
+ }
6928
+ function resolveFileVisibility(file, fallback = "private") {
6929
+ if (file.visibility) return file.visibility;
6930
+ if (file.is_public === true) return "app_public";
6931
+ return fallback;
6932
+ }
6933
+ function shouldGateOnPipeline(policy) {
6934
+ return policy === "safe_public" || policy === "moderated" || policy === "compliance";
6935
+ }
6936
+ function resolvePresetSpec(preset, customWidths) {
6937
+ if (preset === "custom") {
6938
+ const widths = Array.from(
6939
+ new Set((customWidths ?? []).filter((value) => Number.isFinite(value) && value > 0))
6940
+ ).sort((a, b) => a - b);
6941
+ return { widths: widths.length > 0 ? widths : MEDIA_PRESETS.inline.widths };
6942
+ }
6943
+ return MEDIA_PRESETS[preset];
6944
+ }
6945
+ function transformOptions(width, fit) {
6946
+ return fit === "cover" ? { width, height: width, fit: "cover" } : { width, fit: fit ?? "contain" };
6947
+ }
6948
+ function pickDefaultWidth(widths) {
6949
+ if (widths.includes(1200)) return 1200;
6950
+ return widths[Math.floor(widths.length / 2)] ?? widths[0] ?? 0;
6951
+ }
6952
+ function fallbackFileInfo(fileId, contentType, visibility, originalUrl, cdnUrl) {
6953
+ return {
6954
+ id: fileId,
6955
+ filename: fileId,
6956
+ content_type: contentType,
6957
+ size_bytes: 0,
6958
+ is_public: visibility !== "private",
6959
+ visibility,
6960
+ cdn_url: cdnUrl ?? void 0,
6961
+ url: originalUrl ?? void 0,
6962
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
6963
+ };
6964
+ }
6965
+ function normalizeThrownError(error) {
6966
+ if (typeof error === "object" && error && "code" in error && "message" in error) {
6967
+ return error;
6968
+ }
6969
+ return {
6970
+ code: "upload_error",
6971
+ message: error instanceof Error ? error.message : "Media operation failed",
6972
+ status: 500
6973
+ };
6974
+ }
6975
+ function scanError(status) {
6976
+ switch (status) {
6977
+ case "threat":
6978
+ return {
6979
+ code: "file_threat",
6980
+ message: "File was flagged as malicious during scanning.",
6981
+ status: 409
6982
+ };
6983
+ case "quarantined":
6984
+ return {
6985
+ code: "file_quarantined",
6986
+ message: "File was quarantined during scanning.",
6987
+ status: 409
6988
+ };
6989
+ default:
6990
+ return {
6991
+ code: "upload_error",
6992
+ message: "File scan failed.",
6993
+ status: 500
6994
+ };
6995
+ }
6996
+ }
6997
+ function sleep4(ms) {
6998
+ return new Promise((resolve) => setTimeout(resolve, ms));
6999
+ }
7000
+
6322
7001
  // src/services/audio.ts
6323
7002
  var AudioService = class extends ServiceModule {
6324
7003
  /**
@@ -7267,6 +7946,7 @@ var ScaleMule = class {
7267
7946
  this.functions = new FunctionsService(this._client);
7268
7947
  this.photo = new PhotoService(this._client, this.storage);
7269
7948
  this.audio = new AudioService(this._client, this.storage);
7949
+ this.media = new MediaService(this._client, this.storage, this.photo, this.video, this.audio);
7270
7950
  this.tts = new TtsService(this._client);
7271
7951
  this.flagContent = new FlagContentService(this._client);
7272
7952
  this.creatorMaker = new CreatorMakerService(this._client);
@@ -7431,6 +8111,8 @@ export {
7431
8111
  LeaderboardService,
7432
8112
  ListingsService,
7433
8113
  LoggerService,
8114
+ MEDIA_PRESETS,
8115
+ MediaService,
7434
8116
  NotificationsService,
7435
8117
  OrchestratorService,
7436
8118
  PHONE_COUNTRIES,