@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.js CHANGED
@@ -322,6 +322,8 @@ __export(index_exports, {
322
322
  LeaderboardService: () => LeaderboardService,
323
323
  ListingsService: () => ListingsService,
324
324
  LoggerService: () => LoggerService,
325
+ MEDIA_PRESETS: () => MEDIA_PRESETS,
326
+ MediaService: () => MediaService,
325
327
  NotificationsService: () => NotificationsService,
326
328
  OrchestratorService: () => OrchestratorService,
327
329
  PHONE_COUNTRIES: () => PHONE_COUNTRIES,
@@ -2331,6 +2333,24 @@ var DEFAULT_STALL_TIMEOUT_MS = 45e3;
2331
2333
  var SLOW_NETWORK_STALL_TIMEOUT_MS = 9e4;
2332
2334
  var MULTIPART_THRESHOLD = 8 * 1024 * 1024;
2333
2335
  var MULTIPART_THRESHOLD_SLOW = 4 * 1024 * 1024;
2336
+ function buildVisibilityWire(options) {
2337
+ if (!options) return {};
2338
+ if (options.visibility) {
2339
+ return {
2340
+ visibility: options.visibility,
2341
+ // Legacy field for old storage instances that haven't deployed
2342
+ // the tristate handler yet — omit `is_public` for the
2343
+ // `anonymous_visible` case so an old server that doesn't know
2344
+ // the new value at least falls through to its own default
2345
+ // rather than mis-treating it as `app_public`.
2346
+ ...options.visibility === "private" ? { is_public: false } : options.visibility === "app_public" ? { is_public: true } : {}
2347
+ };
2348
+ }
2349
+ if (typeof options.isPublic === "boolean") {
2350
+ return { is_public: options.isPublic };
2351
+ }
2352
+ return {};
2353
+ }
2334
2354
  var StorageService = class extends ServiceModule {
2335
2355
  constructor() {
2336
2356
  super(...arguments);
@@ -2412,6 +2432,42 @@ var StorageService = class extends ServiceModule {
2412
2432
  }
2413
2433
  return result;
2414
2434
  }
2435
+ /**
2436
+ * Upload a file as world-readable on the anonymous public CDN.
2437
+ *
2438
+ * Same browser→S3 pipeline as {@link upload}, but pins
2439
+ * `visibility: 'anonymous_visible'` — caller cannot opt out.
2440
+ *
2441
+ * Use this for media meant to render on logged-out marketing
2442
+ * pages, blog posts, embed snippets — anywhere a customer needs
2443
+ * to drop a URL into `<img src>` without an authenticated
2444
+ * session. For everything else (chat attachments, private
2445
+ * uploads, app-internal galleries) prefer {@link upload} or
2446
+ * {@link uploadPrivate}.
2447
+ *
2448
+ * **`cdn_url` may be `null` on the immediate response.** Storage
2449
+ * intentionally withholds the public CDN URL until the AV scan
2450
+ * has flipped to `clean` — exposing the URL pre-scan would let a
2451
+ * customer embed the bytes in a logged-out page before the
2452
+ * platform has verified them. The upload itself succeeds
2453
+ * regardless; consumers should check `result.data.cdn_url` and:
2454
+ * - if non-null → it's safe to publish
2455
+ * - if null → poll {@link getFileStatus} on a small backoff
2456
+ * until `urls.cdn_url` populates (or `scan.status` flips to
2457
+ * `threat` / `quarantined` / `error` — terminal failure)
2458
+ *
2459
+ * Requires the operator to have provisioned the anonymous
2460
+ * delivery bucket + CDN. When they haven't, the storage service
2461
+ * returns 503 `ANONYMOUS_DELIVERY_NOT_CONFIGURED` (an error
2462
+ * propagated through this helper) — it never silently demotes
2463
+ * to `app_public`.
2464
+ */
2465
+ async uploadAnonymous(file, options) {
2466
+ return this.upload(file, {
2467
+ ...options,
2468
+ visibility: "anonymous_visible"
2469
+ });
2470
+ }
2415
2471
  // --------------------------------------------------------------------------
2416
2472
  // Direct Upload (3-step with retry + stall)
2417
2473
  // --------------------------------------------------------------------------
@@ -2425,7 +2481,7 @@ var StorageService = class extends ServiceModule {
2425
2481
  filename,
2426
2482
  content_type: file.type || "application/octet-stream",
2427
2483
  size_bytes: file.size,
2428
- is_public: options?.isPublic ?? true,
2484
+ ...buildVisibilityWire(options),
2429
2485
  metadata: options?.metadata
2430
2486
  },
2431
2487
  requestOpts
@@ -2516,6 +2572,13 @@ var StorageService = class extends ServiceModule {
2516
2572
  content_type: d.content_type,
2517
2573
  size_bytes: d.size_bytes,
2518
2574
  url: d.url,
2575
+ // Surface visibility + cdn_url all the way out so callers
2576
+ // can branch on visibility without a follow-up getInfo()
2577
+ // round-trip. Anonymous-visible callers especially need
2578
+ // `cdn_url` here to render the image immediately.
2579
+ visibility: d.visibility,
2580
+ cdn_url: d.cdn_url,
2581
+ is_public: d.visibility ? d.visibility !== "private" : void 0,
2519
2582
  created_at: (/* @__PURE__ */ new Date()).toISOString()
2520
2583
  },
2521
2584
  error: null
@@ -2597,7 +2660,7 @@ var StorageService = class extends ServiceModule {
2597
2660
  filename,
2598
2661
  content_type: file.type || "application/octet-stream",
2599
2662
  size_bytes: file.size,
2600
- is_public: options?.isPublic ?? true,
2663
+ ...buildVisibilityWire(options),
2601
2664
  metadata: options?.metadata,
2602
2665
  chunk_size: options?.chunkSize,
2603
2666
  ...clientUploadKey ? { client_upload_key: clientUploadKey } : {}
@@ -2875,6 +2938,9 @@ var StorageService = class extends ServiceModule {
2875
2938
  content_type: d.content_type,
2876
2939
  size_bytes: d.size_bytes,
2877
2940
  url: d.url,
2941
+ visibility: d.visibility,
2942
+ cdn_url: d.cdn_url,
2943
+ is_public: d.visibility ? d.visibility !== "private" : void 0,
2878
2944
  created_at: (/* @__PURE__ */ new Date()).toISOString()
2879
2945
  },
2880
2946
  error: null
@@ -2912,7 +2978,7 @@ var StorageService = class extends ServiceModule {
2912
2978
  {
2913
2979
  filename,
2914
2980
  content_type: contentType,
2915
- is_public: options?.isPublic ?? true,
2981
+ ...buildVisibilityWire(options),
2916
2982
  expires_in: options?.expiresIn ?? 3600,
2917
2983
  size_bytes: options?.sizeBytes,
2918
2984
  metadata: options?.metadata
@@ -2959,7 +3025,16 @@ var StorageService = class extends ServiceModule {
2959
3025
  // --------------------------------------------------------------------------
2960
3026
  // Multipart Public API (for advanced/server-side usage)
2961
3027
  // --------------------------------------------------------------------------
2962
- /** Start a multipart upload session. */
3028
+ /**
3029
+ * Start a multipart upload session.
3030
+ *
3031
+ * Accepts both the typed `visibility` field (preferred) and the
3032
+ * legacy `is_public` boolean for back-compat. If both are sent the
3033
+ * storage service uses `visibility`. `'anonymous_visible'` requires
3034
+ * the operator to have provisioned the anonymous bucket — the
3035
+ * service returns 503 `ANONYMOUS_DELIVERY_NOT_CONFIGURED`
3036
+ * otherwise (the SDK never silently demotes).
3037
+ */
2963
3038
  async startMultipartUpload(params, requestOptions) {
2964
3039
  return this.post("/signed-url/multipart/start", params, requestOptions);
2965
3040
  }
@@ -3090,14 +3165,26 @@ var StorageService = class extends ServiceModule {
3090
3165
  return this._get(`/files/${fileId}/view-status`, options);
3091
3166
  }
3092
3167
  /**
3093
- * Update a file's visibility (public/private).
3094
- * Only the file owner can toggle this. Changes URL TTL — does not move the S3 object.
3095
- * Public files get 7-day signed URLs; private files get 1-hour signed URLs.
3168
+ * Update a file's visibility.
3169
+ *
3170
+ * Accepts either:
3171
+ * - a tri-state {@link Visibility} string (preferred), or
3172
+ * - a legacy boolean (`true` → `app_public`, `false` → `private`).
3173
+ *
3174
+ * Only the file owner / app member can toggle this. Same-bucket
3175
+ * transitions (`private` ↔ `app_public`) succeed and the service
3176
+ * keeps the legacy `is_public` column in sync via a DB trigger.
3177
+ * Cross-bucket transitions (any flip into or out of
3178
+ * `'anonymous_visible'`) currently return 409
3179
+ * `VISIBILITY_TRANSITION_UNSUPPORTED` — the bytes would need to
3180
+ * move between S3 buckets and that orchestration is not yet
3181
+ * shipped. Re-upload the file with the desired visibility instead.
3096
3182
  */
3097
- async updateVisibility(fileId, isPublic, options) {
3183
+ async updateVisibility(fileId, visibility, options) {
3184
+ const body = typeof visibility === "boolean" ? { is_public: visibility } : { visibility };
3098
3185
  return this.patch(
3099
3186
  `/files/${fileId}/visibility`,
3100
- { is_public: isPublic },
3187
+ body,
3101
3188
  options
3102
3189
  );
3103
3190
  }
@@ -6496,6 +6583,41 @@ var PhotoService = class extends ServiceModule {
6496
6583
  const qs = params.toString();
6497
6584
  return `${this.client.getBaseUrl()}${this.basePath}/${photoId}/transform${qs ? `?${qs}` : ""}`;
6498
6585
  }
6586
+ /**
6587
+ * Build an absolute URL for the **public** transform endpoint —
6588
+ * the unauthenticated path that serves transformed bytes for
6589
+ * `<img src>` use on logged-out marketing pages, blogs, embeds.
6590
+ *
6591
+ * The photo service refuses any photo that isn't:
6592
+ * - `visibility = 'anonymous_visible'` (the customer explicitly
6593
+ * opted into world-readable for this file at upload time)
6594
+ * - `scan_status = 'clean'` (no exception for pending/scanning)
6595
+ *
6596
+ * Anything else returns 404 — the endpoint refuses to disambiguate
6597
+ * "not found" from "not anonymous" so it can't be probed to
6598
+ * discover existence or visibility of private photos.
6599
+ *
6600
+ * Pair with {@link getTransformUrl} for the authenticated case:
6601
+ * customer apps that already have a session should keep using the
6602
+ * authed transform URL (which also handles `anonymous_visible`
6603
+ * photos transparently) — this URL is for cross-origin embedding.
6604
+ *
6605
+ * @example
6606
+ * ```tsx
6607
+ * // photo was uploaded with visibility: 'anonymous_visible'
6608
+ * <img src={sm.photo.getPublicTransformUrl(photoId, { width: 800 })} />
6609
+ * ```
6610
+ */
6611
+ getPublicTransformUrl(photoId, options) {
6612
+ const params = new URLSearchParams();
6613
+ if (options?.width) params.set("width", String(options.width));
6614
+ if (options?.height) params.set("height", String(options.height));
6615
+ if (options?.fit) params.set("fit", options.fit);
6616
+ if (options?.format) params.set("format", options.format);
6617
+ if (options?.quality) params.set("quality", String(options.quality));
6618
+ const qs = params.toString();
6619
+ return `${this.client.getBaseUrl()}${this.basePath}/public/${photoId}/transform${qs ? `?${qs}` : ""}`;
6620
+ }
6499
6621
  /**
6500
6622
  * Get a transform URL optimized for the given display area.
6501
6623
  *
@@ -6693,6 +6815,565 @@ var PhotoService = class extends ServiceModule {
6693
6815
  }
6694
6816
  };
6695
6817
 
6818
+ // src/services/media.ts
6819
+ var MEDIA_PRESETS = {
6820
+ hero: { widths: [400, 800, 1200, 1600, 2400] },
6821
+ inline: { widths: [400, 800, 1200] },
6822
+ thumbnail: { widths: [120, 240, 360], fit: "cover" },
6823
+ avatar: { widths: [64, 128, 256], fit: "cover" },
6824
+ logo: { widths: [120, 240, 480] }
6825
+ };
6826
+ var MediaService = class extends ServiceModule {
6827
+ constructor(client, storage, photo, video, audio) {
6828
+ super(client);
6829
+ this.storage = storage;
6830
+ this.photo = photo;
6831
+ this.video = video;
6832
+ this.audio = audio;
6833
+ this.basePath = "";
6834
+ }
6835
+ getPresets() {
6836
+ return MEDIA_PRESETS;
6837
+ }
6838
+ async upload(file, options, requestOptions) {
6839
+ const mimeType = file.type || "application/octet-stream";
6840
+ const kind = detectKind(mimeType);
6841
+ const visibility = resolveVisibility(options);
6842
+ const isPublic = visibility !== "private";
6843
+ const isAnonymous = visibility === "anonymous_visible";
6844
+ const gateOnPipeline = shouldGateOnPipeline(options?.policy);
6845
+ const emit = (phase, progress, fileId) => {
6846
+ options?.onProgress?.({ phase, progress, file_id: fileId });
6847
+ };
6848
+ const uploadOptions = {
6849
+ filename: options?.filename,
6850
+ metadata: options?.metadata,
6851
+ signal: options?.signal,
6852
+ onProgress: (progress) => emit("uploading", progress)
6853
+ };
6854
+ emit("presigning", 0);
6855
+ try {
6856
+ if (isAnonymous) {
6857
+ return await this.uploadAnonymous(file, mimeType, kind, options, requestOptions, uploadOptions, emit);
6858
+ }
6859
+ if (kind === "image" && !options?.skipPhotoRegister) {
6860
+ return await this.uploadImage(
6861
+ file,
6862
+ mimeType,
6863
+ visibility,
6864
+ gateOnPipeline,
6865
+ options,
6866
+ requestOptions,
6867
+ uploadOptions,
6868
+ emit
6869
+ );
6870
+ }
6871
+ if (kind === "video" && visibility === "private") {
6872
+ const result = await this.video.uploadViaStorage(file, uploadOptions, requestOptions);
6873
+ if (result.error || !result.data) {
6874
+ return { data: null, error: result.error };
6875
+ }
6876
+ if (gateOnPipeline) {
6877
+ emit("optimizing", 100, result.data.file_id);
6878
+ await result.data.hls_url_promise;
6879
+ }
6880
+ const info = await this.fetchInfoBestEffort(result.data.file_id, requestOptions);
6881
+ const asset2 = this.buildAsset(
6882
+ info ?? fallbackFileInfo(result.data.file_id, mimeType, visibility, result.data.original_view_url, null),
6883
+ {
6884
+ photoId: null,
6885
+ preset: options?.preset,
6886
+ customWidths: options?.customWidths
6887
+ }
6888
+ );
6889
+ emit("ready", 100, result.data.file_id);
6890
+ return {
6891
+ data: {
6892
+ file_id: result.data.file_id,
6893
+ photo_id: null,
6894
+ original_view_url: result.data.original_view_url,
6895
+ optimized_url_promise: Promise.resolve(null),
6896
+ hls_url_promise: result.data.hls_url_promise,
6897
+ mime_type: mimeType,
6898
+ is_public: false,
6899
+ visibility,
6900
+ cdn_url: null,
6901
+ asset: asset2
6902
+ },
6903
+ error: null
6904
+ };
6905
+ }
6906
+ if (kind === "audio" && visibility === "private") {
6907
+ const result = await this.audio.uploadViaStorage(file, uploadOptions, requestOptions);
6908
+ if (result.error || !result.data) {
6909
+ return { data: null, error: result.error };
6910
+ }
6911
+ const info = await this.fetchInfoBestEffort(result.data.file_id, requestOptions);
6912
+ const asset2 = this.buildAsset(
6913
+ info ?? fallbackFileInfo(result.data.file_id, mimeType, visibility, result.data.original_view_url, null),
6914
+ {
6915
+ photoId: null,
6916
+ preset: options?.preset,
6917
+ customWidths: options?.customWidths
6918
+ }
6919
+ );
6920
+ emit("ready", 100, result.data.file_id);
6921
+ return {
6922
+ data: {
6923
+ file_id: result.data.file_id,
6924
+ photo_id: null,
6925
+ original_view_url: result.data.original_view_url,
6926
+ optimized_url_promise: Promise.resolve(null),
6927
+ hls_url_promise: Promise.resolve(null),
6928
+ mime_type: mimeType,
6929
+ is_public: false,
6930
+ visibility,
6931
+ cdn_url: null,
6932
+ asset: asset2
6933
+ },
6934
+ error: null
6935
+ };
6936
+ }
6937
+ const storageResult = isPublic ? await this.storage.upload(file, {
6938
+ ...uploadOptions,
6939
+ visibility: "app_public",
6940
+ skipCompression: true
6941
+ }) : await this.storage.uploadPrivate(file, uploadOptions);
6942
+ if (storageResult.error || !storageResult.data) {
6943
+ return { data: null, error: storageResult.error };
6944
+ }
6945
+ const fileInfo = storageResult.data;
6946
+ const asset = this.buildAsset(fileInfo, {
6947
+ photoId: null,
6948
+ preset: options?.preset,
6949
+ customWidths: options?.customWidths
6950
+ });
6951
+ emit("ready", 100, fileInfo.id);
6952
+ return {
6953
+ data: {
6954
+ file_id: fileInfo.id,
6955
+ photo_id: null,
6956
+ original_view_url: fileInfo.url ?? null,
6957
+ optimized_url_promise: Promise.resolve(null),
6958
+ hls_url_promise: Promise.resolve(null),
6959
+ mime_type: mimeType,
6960
+ is_public: fileInfo.is_public ?? isPublic,
6961
+ visibility: resolveFileVisibility(fileInfo, visibility),
6962
+ cdn_url: fileInfo.cdn_url ?? null,
6963
+ asset
6964
+ },
6965
+ error: null
6966
+ };
6967
+ } catch (error) {
6968
+ return {
6969
+ data: null,
6970
+ error: normalizeThrownError(error)
6971
+ };
6972
+ }
6973
+ }
6974
+ async get(fileId, options, requestOptions) {
6975
+ const result = await this.storage.getInfo(fileId, requestOptions);
6976
+ if (result.error || !result.data) {
6977
+ return { data: null, error: result.error };
6978
+ }
6979
+ return {
6980
+ data: this.buildAsset(result.data, {
6981
+ photoId: null,
6982
+ preset: options?.preset,
6983
+ customWidths: options?.customWidths
6984
+ }),
6985
+ error: null
6986
+ };
6987
+ }
6988
+ async list(params, requestOptions) {
6989
+ const result = await this.storage.list(params, requestOptions);
6990
+ return {
6991
+ data: result.data.map(
6992
+ (file) => this.buildAsset(file, {
6993
+ photoId: null,
6994
+ preset: params?.preset,
6995
+ customWidths: params?.customWidths
6996
+ })
6997
+ ),
6998
+ metadata: result.metadata,
6999
+ error: result.error
7000
+ };
7001
+ }
7002
+ async delete(fileId, options) {
7003
+ try {
7004
+ const [, storageResult] = await Promise.all([
7005
+ this.photo.delete(fileId, options).catch(() => ({ data: null, error: null })),
7006
+ this.storage.delete(fileId, options)
7007
+ ]);
7008
+ if (storageResult.error && storageResult.error.status !== 404) {
7009
+ return { data: null, error: storageResult.error };
7010
+ }
7011
+ return { data: { deleted: true }, error: null };
7012
+ } catch (error) {
7013
+ return { data: null, error: normalizeThrownError(error) };
7014
+ }
7015
+ }
7016
+ async releaseQuarantine(fileId, reason = "Released via @scalemule/sdk media.releaseQuarantine()", options) {
7017
+ const response = await this.client.post(
7018
+ `/v1/storage/admin/files/${fileId}/scan-override`,
7019
+ { scan_status: "clean", reason },
7020
+ options
7021
+ );
7022
+ if (response.error) {
7023
+ return { data: null, error: response.error };
7024
+ }
7025
+ return this.get(fileId, void 0, options);
7026
+ }
7027
+ async getManifest(fileId, options, requestOptions) {
7028
+ const asset = await this.get(fileId, options, requestOptions);
7029
+ if (asset.error || !asset.data) {
7030
+ return { data: null, error: asset.error };
7031
+ }
7032
+ return { data: asset.data.manifest, error: null };
7033
+ }
7034
+ buildAsset(file, options) {
7035
+ const visibility = resolveFileVisibility(file);
7036
+ const photoId = options?.photoId ?? null;
7037
+ const originalUrl = visibility === "anonymous_visible" ? file.cdn_url ?? file.url ?? null : file.url ?? file.cdn_url ?? null;
7038
+ return {
7039
+ file_id: file.id,
7040
+ photo_id: photoId,
7041
+ filename: file.filename,
7042
+ content_type: file.content_type,
7043
+ size_bytes: file.size_bytes,
7044
+ kind: detectKind(file.content_type),
7045
+ visibility,
7046
+ is_public: file.is_public ?? visibility !== "private",
7047
+ scan_status: file.scan_status,
7048
+ created_at: file.created_at,
7049
+ original_url: originalUrl,
7050
+ cdn_url: file.cdn_url ?? null,
7051
+ manifest: this.buildManifest(file, options)
7052
+ };
7053
+ }
7054
+ buildManifest(file, options) {
7055
+ const kind = detectKind(file.content_type);
7056
+ const visibility = resolveFileVisibility(file);
7057
+ const originalUrl = visibility === "anonymous_visible" ? file.cdn_url ?? file.url ?? null : file.url ?? file.cdn_url ?? null;
7058
+ if (!originalUrl) {
7059
+ return null;
7060
+ }
7061
+ if (kind !== "image" || file.content_type === "image/svg+xml") {
7062
+ return {
7063
+ file_id: file.id,
7064
+ content_type: file.content_type,
7065
+ preset: "original",
7066
+ variants: { original: originalUrl },
7067
+ srcset: null,
7068
+ default: originalUrl
7069
+ };
7070
+ }
7071
+ const preset = options?.preset ?? "inline";
7072
+ const spec = resolvePresetSpec(preset, options?.customWidths);
7073
+ const variants = Object.fromEntries(
7074
+ spec.widths.map((width) => [
7075
+ String(width),
7076
+ visibility === "anonymous_visible" ? this.photo.getPublicTransformUrl(file.id, transformOptions(width, spec.fit)) : this.photo.getTransformUrl(file.id, transformOptions(width, spec.fit))
7077
+ ])
7078
+ );
7079
+ const defaultWidth = pickDefaultWidth(spec.widths);
7080
+ const defaultUrl = variants[String(defaultWidth)] ?? Object.values(variants)[0] ?? originalUrl;
7081
+ return {
7082
+ file_id: file.id,
7083
+ content_type: file.content_type,
7084
+ preset,
7085
+ variants,
7086
+ srcset: spec.widths.map((width) => `${variants[String(width)]} ${width}w`).join(", "),
7087
+ default: defaultUrl
7088
+ };
7089
+ }
7090
+ async uploadAnonymous(file, mimeType, kind, options, requestOptions, uploadOptions, emit) {
7091
+ const result = await this.storage.uploadAnonymous(file, uploadOptions);
7092
+ if (result.error || !result.data) {
7093
+ return { data: null, error: result.error };
7094
+ }
7095
+ emit("scanning", 100, result.data.id);
7096
+ const ready = await this.waitForAnonymousReady(result.data.id, options?.signal, emit);
7097
+ if (ready.error) {
7098
+ return { data: null, error: ready.error };
7099
+ }
7100
+ const fileInfo = await this.fetchInfoBestEffort(result.data.id, requestOptions) ?? {
7101
+ ...result.data,
7102
+ cdn_url: ready.cdnUrl ?? result.data.cdn_url,
7103
+ scan_status: ready.scanStatus
7104
+ };
7105
+ const manifest = this.buildManifest(fileInfo, {
7106
+ preset: options?.preset,
7107
+ customWidths: options?.customWidths
7108
+ });
7109
+ if (kind === "image" && fileInfo.content_type !== "image/svg+xml" && options?.prewarm !== false) {
7110
+ emit("optimizing", 100, result.data.id);
7111
+ await this.prewarmManifest(manifest, options?.signal);
7112
+ }
7113
+ const asset = this.buildAsset(fileInfo, {
7114
+ photoId: null,
7115
+ preset: options?.preset,
7116
+ customWidths: options?.customWidths
7117
+ });
7118
+ emit("ready", 100, result.data.id);
7119
+ return {
7120
+ data: {
7121
+ file_id: result.data.id,
7122
+ photo_id: null,
7123
+ original_view_url: fileInfo.cdn_url ?? null,
7124
+ optimized_url_promise: Promise.resolve(manifest?.default ?? null),
7125
+ hls_url_promise: Promise.resolve(null),
7126
+ mime_type: mimeType,
7127
+ is_public: true,
7128
+ visibility: "anonymous_visible",
7129
+ cdn_url: fileInfo.cdn_url ?? null,
7130
+ asset
7131
+ },
7132
+ error: null
7133
+ };
7134
+ }
7135
+ async uploadImage(file, mimeType, visibility, gateOnPipeline, options, requestOptions, uploadOptions, emit) {
7136
+ if (visibility === "private") {
7137
+ const result = await this.photo.uploadViaStorage(file, uploadOptions, requestOptions);
7138
+ if (result.error || !result.data) {
7139
+ return { data: null, error: result.error };
7140
+ }
7141
+ if (gateOnPipeline) {
7142
+ emit("optimizing", 100, result.data.file_id);
7143
+ await result.data.optimized_url_promise;
7144
+ }
7145
+ const info2 = await this.fetchInfoBestEffort(result.data.file_id, requestOptions);
7146
+ const asset2 = this.buildAsset(
7147
+ info2 ?? fallbackFileInfo(result.data.file_id, mimeType, visibility, result.data.original_view_url, null),
7148
+ {
7149
+ photoId: result.data.photo_id,
7150
+ preset: options?.preset,
7151
+ customWidths: options?.customWidths
7152
+ }
7153
+ );
7154
+ emit("ready", 100, result.data.file_id);
7155
+ return {
7156
+ data: {
7157
+ file_id: result.data.file_id,
7158
+ photo_id: result.data.photo_id,
7159
+ original_view_url: result.data.original_view_url,
7160
+ optimized_url_promise: result.data.optimized_url_promise,
7161
+ hls_url_promise: Promise.resolve(null),
7162
+ mime_type: mimeType,
7163
+ is_public: false,
7164
+ visibility,
7165
+ cdn_url: null,
7166
+ asset: asset2
7167
+ },
7168
+ error: null
7169
+ };
7170
+ }
7171
+ const storageResult = await this.storage.upload(file, {
7172
+ ...uploadOptions,
7173
+ visibility: "app_public",
7174
+ skipCompression: true
7175
+ });
7176
+ if (storageResult.error || !storageResult.data) {
7177
+ return { data: null, error: storageResult.error };
7178
+ }
7179
+ const originalViewUrl = storageResult.data.url ?? null;
7180
+ const registerResult = await this.photo.register({ fileId: storageResult.data.id }, requestOptions);
7181
+ const photoId = registerResult.error || !registerResult.data ? null : registerResult.data.id;
7182
+ const optimizedUrlPromise = photoId ? this.pollPhotoOptimizationComplete(photoId, requestOptions) : Promise.resolve(null);
7183
+ if (gateOnPipeline) {
7184
+ emit("optimizing", 100, storageResult.data.id);
7185
+ await optimizedUrlPromise;
7186
+ }
7187
+ const info = await this.fetchInfoBestEffort(storageResult.data.id, requestOptions) ?? storageResult.data;
7188
+ const asset = this.buildAsset(info, {
7189
+ photoId,
7190
+ preset: options?.preset,
7191
+ customWidths: options?.customWidths
7192
+ });
7193
+ emit("ready", 100, storageResult.data.id);
7194
+ return {
7195
+ data: {
7196
+ file_id: storageResult.data.id,
7197
+ photo_id: photoId,
7198
+ original_view_url: originalViewUrl,
7199
+ optimized_url_promise: optimizedUrlPromise,
7200
+ hls_url_promise: Promise.resolve(null),
7201
+ mime_type: mimeType,
7202
+ is_public: true,
7203
+ visibility,
7204
+ cdn_url: info.cdn_url ?? null,
7205
+ asset
7206
+ },
7207
+ error: null
7208
+ };
7209
+ }
7210
+ async waitForAnonymousReady(fileId, signal, emit) {
7211
+ const delays = [500, 1e3, 1500, 2e3, 2500, 3e3];
7212
+ for (let attempt = 0; attempt < 24; attempt++) {
7213
+ if (signal?.aborted) {
7214
+ return {
7215
+ cdnUrl: null,
7216
+ scanStatus: void 0,
7217
+ error: { code: "aborted", message: "Upload aborted", status: 0 }
7218
+ };
7219
+ }
7220
+ const status = await this.storage.getFileStatus(fileId);
7221
+ if (status.error || !status.data) {
7222
+ await sleep4(delays[Math.min(attempt, delays.length - 1)] ?? 3e3);
7223
+ continue;
7224
+ }
7225
+ const scanStatus = status.data.scan.status;
7226
+ if (status.data.urls.cdn_url) {
7227
+ return { cdnUrl: status.data.urls.cdn_url, scanStatus, error: null };
7228
+ }
7229
+ if (scanStatus === "threat" || scanStatus === "quarantined" || scanStatus === "error") {
7230
+ return {
7231
+ cdnUrl: null,
7232
+ scanStatus,
7233
+ error: scanError(scanStatus)
7234
+ };
7235
+ }
7236
+ emit("scanning", Math.min(99, 10 + attempt * 4), fileId);
7237
+ await sleep4(delays[Math.min(attempt, delays.length - 1)] ?? 3e3);
7238
+ }
7239
+ return {
7240
+ cdnUrl: null,
7241
+ scanStatus: "pending",
7242
+ error: {
7243
+ code: "file_scanning",
7244
+ message: "File scan did not complete in time. Re-fetch the file status and publish once cdn_url appears.",
7245
+ status: 202
7246
+ }
7247
+ };
7248
+ }
7249
+ async fetchInfoBestEffort(fileId, requestOptions) {
7250
+ const result = await this.storage.getInfo(fileId, requestOptions);
7251
+ return result.error || !result.data ? null : result.data;
7252
+ }
7253
+ async pollPhotoOptimizationComplete(photoId, requestOptions) {
7254
+ for (let attempt = 0; attempt < 40; attempt++) {
7255
+ const result = await this.photo.get(photoId, requestOptions);
7256
+ const status = result.data?.optimization_status;
7257
+ if (status === "completed") {
7258
+ return this.photo.getTransformUrl(photoId, { width: 1200 });
7259
+ }
7260
+ await sleep4(250);
7261
+ }
7262
+ return null;
7263
+ }
7264
+ async prewarmManifest(manifest, signal) {
7265
+ if (!manifest || manifest.preset === "original") {
7266
+ return;
7267
+ }
7268
+ const urls = Object.values(manifest.variants);
7269
+ await Promise.all(
7270
+ urls.map(async (url) => {
7271
+ try {
7272
+ const response = await fetch(url, {
7273
+ method: "GET",
7274
+ signal,
7275
+ headers: {
7276
+ Accept: "image/avif,image/webp,image/*,*/*;q=0.8"
7277
+ }
7278
+ });
7279
+ if (!response.ok) {
7280
+ throw new Error(`Prewarm failed with HTTP ${response.status}`);
7281
+ }
7282
+ await response.arrayBuffer();
7283
+ } catch (error) {
7284
+ console.warn("[scalemule-sdk] media prewarm failed", url, error);
7285
+ }
7286
+ })
7287
+ );
7288
+ }
7289
+ };
7290
+ function detectKind(contentType) {
7291
+ if (contentType.startsWith("image/")) return "image";
7292
+ if (contentType.startsWith("video/")) return "video";
7293
+ if (contentType.startsWith("audio/")) return "audio";
7294
+ if (contentType.includes("pdf") || contentType.includes("text/") || contentType.includes("word") || contentType.includes("sheet") || contentType.includes("presentation")) {
7295
+ return "document";
7296
+ }
7297
+ return "other";
7298
+ }
7299
+ function resolveVisibility(options) {
7300
+ if (options?.visibility) return options.visibility;
7301
+ if (options?.isPublic === true) return "app_public";
7302
+ return "private";
7303
+ }
7304
+ function resolveFileVisibility(file, fallback = "private") {
7305
+ if (file.visibility) return file.visibility;
7306
+ if (file.is_public === true) return "app_public";
7307
+ return fallback;
7308
+ }
7309
+ function shouldGateOnPipeline(policy) {
7310
+ return policy === "safe_public" || policy === "moderated" || policy === "compliance";
7311
+ }
7312
+ function resolvePresetSpec(preset, customWidths) {
7313
+ if (preset === "custom") {
7314
+ const widths = Array.from(
7315
+ new Set((customWidths ?? []).filter((value) => Number.isFinite(value) && value > 0))
7316
+ ).sort((a, b) => a - b);
7317
+ return { widths: widths.length > 0 ? widths : MEDIA_PRESETS.inline.widths };
7318
+ }
7319
+ return MEDIA_PRESETS[preset];
7320
+ }
7321
+ function transformOptions(width, fit) {
7322
+ return fit === "cover" ? { width, height: width, fit: "cover" } : { width, fit: fit ?? "contain" };
7323
+ }
7324
+ function pickDefaultWidth(widths) {
7325
+ if (widths.includes(1200)) return 1200;
7326
+ return widths[Math.floor(widths.length / 2)] ?? widths[0] ?? 0;
7327
+ }
7328
+ function fallbackFileInfo(fileId, contentType, visibility, originalUrl, cdnUrl) {
7329
+ return {
7330
+ id: fileId,
7331
+ filename: fileId,
7332
+ content_type: contentType,
7333
+ size_bytes: 0,
7334
+ is_public: visibility !== "private",
7335
+ visibility,
7336
+ cdn_url: cdnUrl ?? void 0,
7337
+ url: originalUrl ?? void 0,
7338
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
7339
+ };
7340
+ }
7341
+ function normalizeThrownError(error) {
7342
+ if (typeof error === "object" && error && "code" in error && "message" in error) {
7343
+ return error;
7344
+ }
7345
+ return {
7346
+ code: "upload_error",
7347
+ message: error instanceof Error ? error.message : "Media operation failed",
7348
+ status: 500
7349
+ };
7350
+ }
7351
+ function scanError(status) {
7352
+ switch (status) {
7353
+ case "threat":
7354
+ return {
7355
+ code: "file_threat",
7356
+ message: "File was flagged as malicious during scanning.",
7357
+ status: 409
7358
+ };
7359
+ case "quarantined":
7360
+ return {
7361
+ code: "file_quarantined",
7362
+ message: "File was quarantined during scanning.",
7363
+ status: 409
7364
+ };
7365
+ default:
7366
+ return {
7367
+ code: "upload_error",
7368
+ message: "File scan failed.",
7369
+ status: 500
7370
+ };
7371
+ }
7372
+ }
7373
+ function sleep4(ms) {
7374
+ return new Promise((resolve) => setTimeout(resolve, ms));
7375
+ }
7376
+
6696
7377
  // src/services/audio.ts
6697
7378
  var AudioService = class extends ServiceModule {
6698
7379
  /**
@@ -7641,6 +8322,7 @@ var ScaleMule = class {
7641
8322
  this.functions = new FunctionsService(this._client);
7642
8323
  this.photo = new PhotoService(this._client, this.storage);
7643
8324
  this.audio = new AudioService(this._client, this.storage);
8325
+ this.media = new MediaService(this._client, this.storage, this.photo, this.video, this.audio);
7644
8326
  this.tts = new TtsService(this._client);
7645
8327
  this.flagContent = new FlagContentService(this._client);
7646
8328
  this.creatorMaker = new CreatorMakerService(this._client);
@@ -7806,6 +8488,8 @@ var index_default = ScaleMule;
7806
8488
  LeaderboardService,
7807
8489
  ListingsService,
7808
8490
  LoggerService,
8491
+ MEDIA_PRESETS,
8492
+ MediaService,
7809
8493
  NotificationsService,
7810
8494
  OrchestratorService,
7811
8495
  PHONE_COUNTRIES,