@viu/emporix-sdk 4.2.4 → 4.3.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/media.cjs CHANGED
@@ -179,37 +179,31 @@ var MediaService = class {
179
179
  });
180
180
  }
181
181
  /**
182
- * Update an asset. The input is a discriminated union mirroring
183
- * {@link create}:
184
- * - `{ kind: "json", body }` — metadata-only patch (BLOB or LINK).
185
- * Sends `application/json`. Used for `refIds`, `details`, `metadata`,
186
- * or `url` changes.
187
- * - `{ kind: "blob", file, body }` — replaces the BLOB file content
188
- * (max 30 MB) AND patches metadata in the same request. Sends
189
- * `multipart/form-data`.
182
+ * Replace an asset (`PUT`, HTTP 204 — nothing is returned). The spec takes one
183
+ * body per asset type, mirrored by the discriminated input:
184
+ * - `{ kind: "json", body }` — a LINK asset, sent as `application/json`. The
185
+ * body is the whole asset: `type: "LINK"`, `access` and `url` are required.
186
+ * - `{ kind: "blob", file, body }` — a BLOB asset, sent as
187
+ * `multipart/form-data`: the file (max 30 MB) and the asset body, both
188
+ * required, so this always replaces the bytes.
190
189
  *
191
- * `type` and `access` are immutable per Emporix — they must match the
192
- * existing asset's values. Optimistic-locking is via `body.metadata.version`;
193
- * the server returns 409 Conflict on a stale version.
190
+ * A BLOB's metadata alone — `refIds`, `details`, mixins — goes through
191
+ * {@link patch}. Earlier versions also took a BLOB as the JSON body and
192
+ * promised the updated asset in return; the spec allows neither.
193
+ *
194
+ * `type` and `access` are immutable. Optimistic locking is via
195
+ * `body.metadata.version`; a stale one gets a 409.
194
196
  */
195
197
  async update(assetId, input, auth = SERVICE) {
198
+ const path = `${this.base()}/${encodeURIComponent(assetId)}`;
196
199
  if (input.kind === "blob") {
197
200
  const fd = new FormData();
198
201
  fd.set("file", input.file);
199
202
  fd.set("body", JSON.stringify(input.body));
200
- return this.ctx.http.request({
201
- method: "PUT",
202
- path: `${this.base()}/${assetId}`,
203
- auth,
204
- body: fd
205
- });
203
+ await this.ctx.http.request({ method: "PUT", path, auth, body: fd });
204
+ return;
206
205
  }
207
- return this.ctx.http.request({
208
- method: "PUT",
209
- path: `${this.base()}/${assetId}`,
210
- auth,
211
- body: input.body
212
- });
206
+ await this.ctx.http.request({ method: "PUT", path, auth, body: input.body });
213
207
  }
214
208
  /**
215
209
  * Partially update an asset with an RFC-6902 JSON-Patch op-array
@@ -392,12 +386,17 @@ var MediaService = class {
392
386
  }
393
387
  /**
394
388
  * Replace the file content of an existing BLOB asset. Sugar over
395
- * {@link update} with `kind: "blob"`. `access` is required because the
396
- * field is immutable and the server validates that the patch matches.
397
- * Pass `version` from `asset.metadata.version` if you want optimistic
398
- * locking (recommended when concurrent writers are possible).
389
+ * {@link update} with `kind: "blob"`, and like it resolves to nothing — the
390
+ * PUT answers 204. `access` is required because the field is immutable and
391
+ * the server validates that the body matches.
392
+ *
393
+ * Pass `version` from `asset.metadata.version` for optimistic locking
394
+ * (recommended when concurrent writers are possible) — a stale one gets a 409.
395
+ * Without it the current version is read first, because the live API rejects
396
+ * an update that carries none; the write then wins over any in between.
399
397
  */
400
398
  async replaceFile(assetId, input, auth = SERVICE) {
399
+ const version = input.version ?? (await this.get(assetId, auth)).metadata?.version ?? 1;
401
400
  const body = {
402
401
  type: "BLOB",
403
402
  access: input.access,
@@ -407,7 +406,7 @@ var MediaService = class {
407
406
  ...input.mimeType ? { mimeType: input.mimeType } : {}
408
407
  }
409
408
  } : {},
410
- ...input.version !== void 0 ? { metadata: { version: input.version } } : {}
409
+ metadata: { version }
411
410
  };
412
411
  return this.update(assetId, { kind: "blob", file: input.file, body }, auth);
413
412
  }
@@ -421,23 +420,42 @@ var MediaService = class {
421
420
  };
422
421
  return this.create({ kind: "link", body }, auth);
423
422
  }
424
- /** Idempotently add a PRODUCT refId to an asset. */
423
+ /**
424
+ * Idempotently add a PRODUCT refId to an asset, through a JSON Patch that
425
+ * appends the one reference, so it works for BLOB and LINK alike and leaves
426
+ * the rest of the asset alone.
427
+ *
428
+ * Resolves to the asset as read back after the patch, because Emporix answers
429
+ * 204 to a reference to a product that does not exist and drops it — check
430
+ * `refIds` rather than trusting the call. Only a PUBLIC asset takes a product
431
+ * reference; a PRIVATE one answers 400.
432
+ *
433
+ * Earlier versions sent a JSON PUT of `{ type, refIds }`, which the spec
434
+ * rejects for both types: a BLOB takes no JSON PUT, and a LINK's requires
435
+ * `access` and `url`.
436
+ */
425
437
  async attachToProduct(assetId, productId, auth = SERVICE) {
426
438
  const a = await this.get(assetId, auth);
427
439
  const refIds = a.refIds ?? [];
428
440
  if (refIds.some((r) => isProductRef(r, productId))) return a;
429
- const next = [...refIds, { type: "PRODUCT", id: productId }];
430
- const patch = { type: a.type, refIds: next };
431
- return this.update(assetId, { kind: "json", body: patch }, auth);
441
+ const ref = { type: "PRODUCT", id: productId };
442
+ const op = a.refIds === void 0 ? { op: "add", path: "/refIds", value: [ref] } : { op: "add", path: "/refIds/-", value: ref };
443
+ await this.patch(assetId, [op], auth);
444
+ return this.get(assetId, auth);
432
445
  }
433
- /** Remove a PRODUCT refId from an asset (no-op if absent). */
446
+ /**
447
+ * Remove a PRODUCT refId from an asset (no-op if absent), through a JSON Patch
448
+ * that replaces the references and nothing else. Resolves to the asset as
449
+ * read back after the patch, like {@link attachToProduct}. Earlier versions
450
+ * sent a spec-invalid JSON PUT, as that one did.
451
+ */
434
452
  async detachFromProduct(assetId, productId, auth = SERVICE) {
435
453
  const a = await this.get(assetId, auth);
436
454
  const refIds = a.refIds ?? [];
437
455
  const next = refIds.filter((r) => !isProductRef(r, productId));
438
456
  if (next.length === refIds.length) return a;
439
- const patch = { type: a.type, refIds: next };
440
- return this.update(assetId, { kind: "json", body: patch }, auth);
457
+ await this.patch(assetId, [{ op: "replace", path: "/refIds", value: next }], auth);
458
+ return this.get(assetId, auth);
441
459
  }
442
460
  /** Convenience: list assets attached to a product (server-side filter). */
443
461
  async listForProduct(productId, auth = SERVICE) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/paged.ts","../src/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AAU,EAAC;AAC1C,IAAA,MAAM,IAAA,GAAO,OAAO,MAAA,CAAO,CAAC,MAAM,CAAC,YAAA,CAAa,CAAA,EAAG,SAAS,CAAC,CAAA;AAC7D,IAAA,IAAI,IAAA,CAAK,MAAA,KAAW,MAAA,CAAO,MAAA,EAAQ,OAAO,CAAA;AAC1C,IAAA,MAAM,QAAQ,EAAE,IAAA,EAAM,CAAA,CAAE,IAAA,EAAM,QAAQ,IAAA,EAAK;AAC3C,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,EAAS,EAAE,MAAM,MAAA,EAAQ,IAAA,EAAM,KAAA,EAAM,EAAG,IAAI,CAAA;AAAA,EACjE;AAAA;AAAA,EAGA,MAAM,cAAA,CACJ,SAAA,EACA,IAAA,GAAoB,OAAA,EACY;AAChC,IAAA,OAAO,KAAK,IAAA,CAAK,EAAE,WAAA,EAAa,SAAA,IAAa,IAAI,CAAA;AAAA,EACnD;AACF;AAIO,IAAM,cAAA,GAAiB,EAAE,YAAA","file":"media.cjs","sourcesContent":["import type { PaginatedItems } from \"./context\";\nimport type { HttpClient, RequestOptions } from \"./http\";\n\n/** Pagination inputs for {@link requestPage}. */\nexport interface PageParams {\n /** 1-based, as Emporix counts. */\n pageNumber: number;\n pageSize: number;\n /**\n * Ask Emporix for the absolute match count via the `X-Total-Count: true`\n * request header.\n *\n * Off by default and opt-in per call, not a client-wide setting: the count\n * costs the server a second query, and defaulting it on would put that cost\n * on every list every storefront issues.\n */\n totalCount?: boolean;\n}\n\n/**\n * Reads a non-negative integer header, or `undefined` when it is missing or is\n * not one. A malformed value must not reach the `hasNextPage` arithmetic —\n * `Number(\"lots\")` is `NaN`, and every comparison against `NaN` is `false`,\n * which would silently report \"last page\" on every page.\n */\nfunction intHeader(headers: Headers, name: string): number | undefined {\n const raw = headers.get(name);\n if (raw === null || raw.trim() === \"\") return undefined;\n const n = Number(raw);\n return Number.isInteger(n) && n >= 0 ? n : undefined;\n}\n\n/**\n * Issues one page of a list endpoint and assembles {@link PaginatedItems} from\n * the body plus Emporix's pagination response headers.\n *\n * Cursors travel in opposite directions: the caller sends one as the `next` or\n * `prev` **query parameter** (so it belongs in `o.query`), and the server\n * returns the following one as the `X-Next-Cursor` **response header**. This\n * helper only ever reads them.\n */\nexport async function requestPage<T>(\n http: HttpClient,\n o: RequestOptions,\n page: PageParams,\n): Promise<PaginatedItems<T>> {\n const { data, headers } = await http.requestWithMeta<T[]>(\n page.totalCount === true\n ? { ...o, headers: { ...(o.headers ?? {}), \"X-Total-Count\": \"true\" } }\n : o,\n );\n\n // A 204 or empty body parses to `undefined`. Facades used to index straight\n // into the result and would throw; an empty page is the honest answer.\n const items = data ?? [];\n const totalCount = intHeader(headers, \"X-Total-Count\");\n const nextCursor = headers.get(\"X-Next-Cursor\") ?? undefined;\n const prevCursor = headers.get(\"X-Prev-Cursor\") ?? undefined;\n\n // Three tiers, most precise first. Tier 1 is ONE-DIRECTIONAL on purpose: only\n // two endpoints in the whole API emit a cursor header, so its absence says\n // nothing at all and has to fall through to the other two.\n const hasNextPage =\n nextCursor !== undefined\n ? true\n : totalCount !== undefined\n ? page.pageNumber * page.pageSize < totalCount\n : items.length === page.pageSize;\n\n // Spread conditionally — `exactOptionalPropertyTypes` rejects an explicit\n // `undefined` for an optional property.\n return {\n items,\n pageNumber: page.pageNumber,\n pageSize: page.pageSize,\n hasNextPage,\n ...(totalCount === undefined ? {} : { totalCount }),\n ...(nextCursor === undefined ? {} : { nextCursor }),\n ...(prevCursor === undefined ? {} : { prevCursor }),\n };\n}\n","/** Keys whose values are stripped from any serialised error body. */\nconst REDACTED_BODY_KEYS = new Set([\n \"access_token\", \"refresh_token\", \"token\", \"customertoken\", \"saastoken\",\n \"secret\", \"client_secret\", \"authorization\", \"password\",\n]);\n\nfunction scrub(body: unknown): unknown {\n if (Array.isArray(body)) return body.map(scrub);\n if (body && typeof body === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(body as Record<string, unknown>)) {\n out[k] = REDACTED_BODY_KEYS.has(k.toLowerCase()) ? \"***redacted***\" : scrub(v);\n }\n return out;\n }\n return body;\n}\n\n/** Base class for every error thrown by the SDK. */\nexport class EmporixError extends Error {\n readonly status: number | undefined;\n readonly body: unknown;\n constructor(message: string, status?: number, body?: unknown) {\n super(message);\n this.name = new.target.name;\n this.status = status;\n this.body = body;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n /** Safe serialisation — token-like body fields are redacted. */\n toJSON(): Record<string, unknown> {\n return { name: this.name, message: this.message, status: this.status, body: scrub(this.body) };\n }\n}\n\n/** 401 — authentication failed or token expired. */\nexport class EmporixAuthError extends EmporixError {}\n/** 403 — authenticated but not permitted. */\nexport class EmporixForbiddenError extends EmporixError {}\n/** 404 — resource not found. */\nexport class EmporixNotFoundError extends EmporixError {}\n/** 400/422 — request validation failed. */\nexport class EmporixValidationError extends EmporixError {}\n/** 5xx — server-side failure. */\nexport class EmporixServerError extends EmporixError {}\n/** Request aborted by the configured connect/read timeout. No HTTP status. */\nexport class EmporixTimeoutError extends EmporixError {}\n/** DNS/TLS/connection-level failure before or during the exchange. No HTTP status. */\nexport class EmporixNetworkError extends EmporixError {}\n\n/**\n * 403 with a `missing scope: <name>` hint in the body's `details` array.\n * Subclasses {@link EmporixForbiddenError} so existing 403 catches still work.\n */\nexport class EmporixInsufficientScopeError extends EmporixForbiddenError {\n readonly requiredScope: string | undefined;\n constructor(message: string, status: number, body: unknown, requiredScope?: string) {\n super(message, status, body);\n this.requiredScope = requiredScope;\n }\n}\n\nconst SCOPE_HINT_RE = /missing scope[: ]+([a-z0-9._-]+)/i;\n\nfunction extractRequiredScope(body: unknown): string | undefined {\n if (body && typeof body === \"object\" && \"details\" in body) {\n const details = (body as { details?: unknown }).details;\n if (Array.isArray(details)) {\n for (const d of details) {\n if (typeof d === \"string\") {\n const m = d.match(SCOPE_HINT_RE);\n if (m) return m[1];\n }\n }\n }\n }\n return undefined;\n}\n\n/** Maps an HTTP status to the matching {@link EmporixError} subclass. */\nexport function errorFromResponse(status: number, message: string, body: unknown): EmporixError {\n if (status === 401) return new EmporixAuthError(message, status, body);\n if (status === 403) {\n const scope = extractRequiredScope(body);\n if (scope) return new EmporixInsufficientScopeError(message, status, body, scope);\n return new EmporixForbiddenError(message, status, body);\n }\n if (status === 404) return new EmporixNotFoundError(message, status, body);\n if (status === 400 || status === 422) return new EmporixValidationError(message, status, body);\n if (status >= 500) return new EmporixServerError(message, status, body);\n return new EmporixError(message, status, body);\n}\n","import type { ClientContext, PaginatedItems } from \"../core/context\";\nimport { requestPage } from \"../core/paged\";\nimport type { AuthContext } from \"../core/auth\";\nimport { EmporixError, errorFromResponse } from \"../core/errors\";\nimport type {\n AssetCreateBlob,\n AssetCreateLink,\n AssetUpdateBlob,\n AssetUpdateLink,\n DownloadUrl,\n GetAsset,\n GetMediaRetrieveDownloadUrlData,\n PatchOperation,\n RefId,\n UploadSession,\n UploadSessionRequest,\n} from \"../generated/media\";\n\n/** Generated media types (caller sends the exact wire shape). */\nexport type AssetCreateBlobInput = AssetCreateBlob;\nexport type AssetCreateLinkInput = AssetCreateLink;\nexport type AssetUpdateBlobInput = AssetUpdateBlob;\nexport type AssetUpdateLinkInput = AssetUpdateLink;\nexport type AssetUpdateInput = AssetUpdateBlob | AssetUpdateLink;\nexport type Asset = GetAsset;\nexport type AssetRefId = RefId;\n/** Partial-update body (`PATCH /assets/{id}`) — an RFC-6902 JSON-Patch op-array. */\nexport type AssetPatch = PatchOperation[];\n/** Result of {@link MediaService.getDownloadUrl} — `{ provider, url, expiresAt? }`. */\nexport type AssetDownloadUrl = DownloadUrl;\n/** Query for {@link MediaService.getDownloadUrl} — `{ disposition? }`. */\nexport type AssetDownloadUrlQuery = NonNullable<GetMediaRetrieveDownloadUrlData[\"query\"]>;\n/** Body for {@link MediaService.startUploadSession}: a BLOB create payload plus `uploadType`. */\nexport type AssetUploadSessionInput = UploadSessionRequest;\n/** The storage instruction {@link MediaService.startUploadSession} returns. */\nexport type AssetUploadSession = UploadSession;\n\n/**\n * Filter / pagination options for {@link MediaService.list}. The explicit\n * fields are typed for autocomplete; the index signature stays open so\n * Emporix `q`-syntax filters like `\"refIds.id\"` can be passed verbatim.\n */\nexport interface ListAssetsQuery {\n pageNumber?: number;\n pageSize?: number;\n /** Emporix sort syntax, e.g. `\"name,metadata.createdAt:desc\"`. */\n sort?: string;\n /** Emporix `q`-syntax filter, e.g. `\"name:hero\"`. */\n q?: string;\n /**\n * Ask for `X-Total-Count`. An SDK-side flag, not an Emporix query parameter:\n * it becomes a request header.\n */\n totalCount?: boolean;\n [key: string]: string | number | boolean | undefined;\n}\n\n/**\n * Result of {@link MediaService.download}. The endpoint's behaviour depends\n * on the asset's `access`:\n * - `PUBLIC` assets respond with a 30x redirect whose `Location` header\n * carries the externally-cacheable storage URL — useful when the\n * storefront wants to send the user there directly.\n * - `PRIVATE` assets respond with the raw bytes (plus an `ETag` header\n * for caching). The file lives in Google Cloud Storage and is reachable\n * without the service token only through a signed URL from\n * {@link MediaService.getDownloadUrl}.\n */\nexport type DownloadResult =\n | { kind: \"redirect\"; url: string }\n | {\n kind: \"bytes\";\n data: ArrayBuffer;\n etag?: string;\n contentType?: string;\n };\n\nconst SERVICE: AuthContext = { kind: \"service\" };\n\nfunction isProductRef(r: AssetRefId, productId: string): boolean {\n return r.type === \"PRODUCT\" && r.id === productId;\n}\n\n/**\n * Media assets (BLOB/LINK). All endpoints require a backend-only scope\n * (`media.asset_manage` / `media.asset_read`) — default auth: service.\n */\nexport class MediaService {\n static readonly channel = \"media\" as const;\n constructor(private readonly ctx: ClientContext) {}\n\n private base(): string {\n return `/media/${this.ctx.tenant}/assets`;\n }\n\n /**\n * Create an asset. BLOB uploads via multipart (max 30 MB); LINK via JSON.\n * {@link startUploadSession} sends the file straight to storage instead.\n */\n async create(\n input:\n | { kind: \"blob\"; file: Blob; body: AssetCreateBlobInput }\n | { kind: \"link\"; body: AssetCreateLinkInput },\n auth: AuthContext = SERVICE,\n ): Promise<{ id: string }> {\n if (input.kind === \"blob\") {\n const fd = new FormData();\n fd.set(\"file\", input.file);\n fd.set(\"body\", JSON.stringify(input.body));\n return this.ctx.http.request<{ id: string }>({\n method: \"POST\",\n path: this.base(),\n auth,\n body: fd,\n });\n }\n return this.ctx.http.request<{ id: string }>({\n method: \"POST\",\n path: this.base(),\n auth,\n body: input.body,\n });\n }\n\n /**\n * List assets, wrapped in the shared {@link PaginatedItems} envelope so\n * callers can iterate over pages consistently with the rest of the SDK.\n * `hasNextPage` is the standard SDK heuristic: `true` when the returned\n * page is full (`items.length === requested pageSize`). Pagination\n * defaults match Emporix's server defaults (`pageNumber: 1`,\n * `pageSize: 60`) so an empty `query` produces stable expectations.\n */\n async list(\n query: ListAssetsQuery = {},\n auth: AuthContext = SERVICE,\n ): Promise<PaginatedItems<Asset>> {\n const pageNumber = query.pageNumber ?? 1;\n const pageSize = query.pageSize ?? 60;\n // Destructured out because the rest of `query` is spread into the query\n // string: `totalCount` is an SDK-side flag that becomes a request header,\n // and would otherwise ride along as a stray `?totalCount=true`.\n const { totalCount, ...rest } = query;\n return requestPage<Asset>(\n this.ctx.http,\n {\n method: \"GET\",\n path: this.base(),\n auth,\n query: { ...rest, pageNumber, pageSize },\n },\n { pageNumber, pageSize, ...(totalCount === undefined ? {} : { totalCount }) },\n );\n }\n\n /** Fetch an asset by id. */\n async get(assetId: string, auth: AuthContext = SERVICE): Promise<Asset> {\n return this.ctx.http.request<Asset>({\n method: \"GET\",\n path: `${this.base()}/${assetId}`,\n auth,\n });\n }\n\n /**\n * Update an asset. The input is a discriminated union mirroring\n * {@link create}:\n * - `{ kind: \"json\", body }` — metadata-only patch (BLOB or LINK).\n * Sends `application/json`. Used for `refIds`, `details`, `metadata`,\n * or `url` changes.\n * - `{ kind: \"blob\", file, body }` — replaces the BLOB file content\n * (max 30 MB) AND patches metadata in the same request. Sends\n * `multipart/form-data`.\n *\n * `type` and `access` are immutable per Emporix — they must match the\n * existing asset's values. Optimistic-locking is via `body.metadata.version`;\n * the server returns 409 Conflict on a stale version.\n */\n async update(\n assetId: string,\n input:\n | { kind: \"json\"; body: AssetUpdateInput }\n | { kind: \"blob\"; file: Blob; body: AssetUpdateBlobInput },\n auth: AuthContext = SERVICE,\n ): Promise<Asset> {\n if (input.kind === \"blob\") {\n const fd = new FormData();\n fd.set(\"file\", input.file);\n fd.set(\"body\", JSON.stringify(input.body));\n return this.ctx.http.request<Asset>({\n method: \"PUT\",\n path: `${this.base()}/${assetId}`,\n auth,\n body: fd,\n });\n }\n return this.ctx.http.request<Asset>({\n method: \"PUT\",\n path: `${this.base()}/${assetId}`,\n auth,\n body: input.body,\n });\n }\n\n /**\n * Partially update an asset with an RFC-6902 JSON-Patch op-array\n * (`PATCH /assets/{id}`, HTTP 204 — nothing is returned).\n *\n * This is the way to change one field without resending the whole asset, and\n * the only way to touch a `BLOB` asset's metadata **without re-uploading the\n * file** — {@link update} in `blob` mode always replaces the bytes.\n *\n * Append to an array with a path ending in `/-`, which preserves the existing\n * entries:\n *\n * ```ts\n * await client.media.patch(assetId, [\n * { op: \"add\", path: \"/refIds/-\", value: { id: \"product1\", type: \"PRODUCT\" } },\n * ]);\n * ```\n *\n * `type` and `access` are immutable here too, as with {@link update}. Only\n * `add`, `remove` and `replace` are accepted, and optimistic locking still\n * applies — a stale `metadata.version` gets a 409.\n */\n async patch(assetId: string, ops: AssetPatch, auth: AuthContext = SERVICE): Promise<void> {\n await this.ctx.http.request<void>({\n method: \"PATCH\",\n path: `${this.base()}/${encodeURIComponent(assetId)}`,\n auth,\n body: ops,\n });\n }\n\n /** Remove an asset. */\n async remove(assetId: string, auth: AuthContext = SERVICE): Promise<void> {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `${this.base()}/${assetId}`,\n auth,\n });\n }\n\n /**\n * Download an asset by id. Returns a discriminated union:\n * - `{ kind: \"redirect\", url }` for `PUBLIC` assets (server-side 30x with\n * the storage URL in `Location`).\n * - `{ kind: \"bytes\", data }` for `PRIVATE` assets (server-side 200 with\n * the asset bytes; `etag` + `contentType` headers are exposed for\n * caching). When the server reports `text/plain` Content-Type (the\n * OpenAPI-documented format), the SDK decodes the base64 stream into\n * an `ArrayBuffer` transparently; binary Content-Types are passed\n * through verbatim.\n *\n * Emporix recommends {@link getDownloadUrl} for every download: here the file\n * passes through the Media API. A `413` means the asset's known size exceeds\n * the streaming limit (30 MB by default) — only {@link getDownloadUrl} can\n * serve it. A `409` means the asset is still `PENDING` from a direct upload\n * whose file has not reached storage.\n *\n * Implementation note: uses `redirect: \"manual\"` so the redirect-location\n * is observable. In Node.js this works; in a browser the redirect Location\n * is intentionally hidden by fetch — there, `PUBLIC` downloads will\n * surface as an opaque-redirect and the SDK throws. Browser code should\n * use the asset's `url` field from `get()` for `LINK` assets, or the\n * direct storage URL for `PUBLIC` `BLOB` assets (typically delivered via\n * an `<img>` tag rather than `download()`).\n */\n async download(\n assetId: string,\n auth: AuthContext = SERVICE,\n ): Promise<DownloadResult> {\n const path = `${this.base()}/${assetId}/download`;\n const res = await this.ctx.http.requestRaw(\n { method: \"GET\", path, auth },\n { redirect: \"manual\" },\n );\n\n // PUBLIC: server-side redirect — capture Location.\n if (res.status >= 300 && res.status < 400) {\n const url = res.headers.get(\"location\");\n if (!url) {\n throw new EmporixError(\n `media.download: ${res.status} response without a Location header`,\n res.status,\n );\n }\n return { kind: \"redirect\", url };\n }\n\n // PRIVATE: bytes.\n if (res.ok) {\n const etag = res.headers.get(\"etag\") ?? undefined;\n const contentType = res.headers.get(\"content-type\") ?? undefined;\n let data: ArrayBuffer;\n if (contentType?.startsWith(\"text/plain\")) {\n // Per OpenAPI spec the server returns the byte stream as a\n // base64-encoded text/plain body. Decode once into raw bytes\n // so callers always see an ArrayBuffer.\n const text = await res.text();\n const bin = atob(text);\n const arr = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);\n data = arr.buffer;\n } else {\n data = await res.arrayBuffer();\n }\n return {\n kind: \"bytes\",\n data,\n ...(etag !== undefined ? { etag } : {}),\n ...(contentType !== undefined ? { contentType } : {}),\n };\n }\n\n // Error: surface via the standard EmporixError hierarchy.\n const text = await res.text();\n let parsed: unknown = undefined;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = text;\n }\n }\n throw errorFromResponse(res.status, `GET ${path} → ${res.status}`, parsed);\n }\n\n /**\n * Get a URL that serves the stored file straight from storage\n * (`GET /assets/{assetId}/download-url`). Emporix recommends it for every\n * download: the file never passes through the Media API, there is no size\n * limit, and the URL can be handed to a browser as it is.\n *\n * - `PRIVATE` BLOB → `provider: \"GCS\"`, a signed Google Cloud Storage URL that\n * works without an Emporix token until `expiresAt` (15 minutes by default).\n * - `PUBLIC` BLOB → `provider: \"CLOUDINARY\"`, the permanent URL.\n * - `LINK` → `provider: \"LINK\"`, the stored URL.\n *\n * `disposition` (`attachment` by default, or `inline`) affects private URLs\n * only. Unlike {@link startUploadSession}, this works whether or not direct\n * upload is enabled for the tenant. A `409` means a direct upload is still\n * `PENDING` and its file has not reached storage; once it has, this call\n * completes the asset before answering.\n */\n async getDownloadUrl(\n assetId: string,\n query: AssetDownloadUrlQuery = {},\n auth: AuthContext = SERVICE,\n ): Promise<AssetDownloadUrl> {\n return this.ctx.http.request<AssetDownloadUrl>({\n method: \"GET\",\n path: `${this.base()}/${encodeURIComponent(assetId)}/download-url`,\n auth,\n query: { ...query },\n });\n }\n\n /**\n * Start a direct upload of a `BLOB` asset (`POST /assets/upload-session`,\n * `201`). Emporix creates the asset as `PENDING` — `id` is its id — and\n * returns where to send the file. **This method does not send it**:\n *\n * - `upload.method === \"PUT\"` (a `PRIVATE` asset, `uploadType: \"put\"` or\n * omitted): `PUT` the file to `upload.url` with every `upload.headers` entry.\n * - `upload.method === \"POST\"` (every `PUBLIC` asset, or `uploadType: \"form\"`):\n * a multipart `POST` to `upload.url` with every `upload.fields` entry\n * unchanged and the file part last.\n *\n * That request goes to Google Cloud Storage or Cloudinary, not to Emporix, so\n * it must not carry the Emporix token — which is also why a browser can make\n * it. The asset turns `READY` once storage confirms; until then, calls that\n * need the file answer `409`. The instruction is valid for 15 minutes (GCS) or\n * an hour (Cloudinary), and an unused session expires at `expiresAt`.\n *\n * Direct upload is enabled per tenant by Emporix Support. Without it the call\n * throws an `EmporixForbiddenError` whose `body.message` is `direct upload is\n * not enabled for this tenant`, and nothing is created — the same status as a\n * missing scope, so read the message.\n */\n async startUploadSession(\n input: AssetUploadSessionInput,\n auth: AuthContext = SERVICE,\n ): Promise<AssetUploadSession> {\n return this.ctx.http.request<AssetUploadSession>({\n method: \"POST\",\n path: `${this.base()}/upload-session`,\n auth,\n body: input,\n });\n }\n\n /** Multipart upload sugar: builds `AssetCreateBlob` from input. */\n async uploadFile(\n input: {\n file: Blob;\n productId?: string;\n filename?: string;\n mimeType?: string;\n access?: \"PUBLIC\" | \"PRIVATE\";\n },\n auth: AuthContext = SERVICE,\n ): Promise<{ id: string }> {\n const body: AssetCreateBlobInput = {\n type: \"BLOB\",\n access: input.access ?? \"PUBLIC\",\n ...(input.productId\n ? { refIds: [{ type: \"PRODUCT\", id: input.productId }] }\n : {}),\n ...(input.filename || input.mimeType\n ? {\n details: {\n ...(input.filename ? { filename: input.filename } : {}),\n ...(input.mimeType ? { mimeType: input.mimeType } : {}),\n },\n }\n : {}),\n };\n return this.create({ kind: \"blob\", file: input.file, body }, auth);\n }\n\n /**\n * Replace the file content of an existing BLOB asset. Sugar over\n * {@link update} with `kind: \"blob\"`. `access` is required because the\n * field is immutable and the server validates that the patch matches.\n * Pass `version` from `asset.metadata.version` if you want optimistic\n * locking (recommended when concurrent writers are possible).\n */\n async replaceFile(\n assetId: string,\n input: {\n file: Blob;\n access: \"PUBLIC\" | \"PRIVATE\";\n filename?: string;\n mimeType?: string;\n version?: number;\n },\n auth: AuthContext = SERVICE,\n ): Promise<Asset> {\n const body: AssetUpdateBlobInput = {\n type: \"BLOB\",\n access: input.access,\n ...(input.filename || input.mimeType\n ? {\n details: {\n ...(input.filename ? { filename: input.filename } : {}),\n ...(input.mimeType ? { mimeType: input.mimeType } : {}),\n },\n }\n : {}),\n ...(input.version !== undefined\n ? { metadata: { version: input.version } }\n : {}),\n };\n return this.update(assetId, { kind: \"blob\", file: input.file, body }, auth);\n }\n\n /** External-URL sugar: builds `AssetCreateLink`. */\n async link(\n input: { url: string; productId?: string; access?: \"PUBLIC\" | \"PRIVATE\" },\n auth: AuthContext = SERVICE,\n ): Promise<{ id: string }> {\n const body: AssetCreateLinkInput = {\n type: \"LINK\",\n access: input.access ?? \"PUBLIC\",\n url: input.url,\n ...(input.productId\n ? { refIds: [{ type: \"PRODUCT\", id: input.productId }] }\n : {}),\n };\n return this.create({ kind: \"link\", body }, auth);\n }\n\n /** Idempotently add a PRODUCT refId to an asset. */\n async attachToProduct(\n assetId: string,\n productId: string,\n auth: AuthContext = SERVICE,\n ): Promise<Asset> {\n const a = await this.get(assetId, auth);\n const refIds: AssetRefId[] = a.refIds ?? [];\n if (refIds.some((r) => isProductRef(r, productId))) return a;\n const next: AssetRefId[] = [...refIds, { type: \"PRODUCT\", id: productId }];\n // Preserve the asset's type discriminator so the update body satisfies\n // the AssetUpdateBlob | AssetUpdateLink union.\n const patch = { type: a.type, refIds: next } as unknown as AssetUpdateInput;\n return this.update(assetId, { kind: \"json\", body: patch }, auth);\n }\n\n /** Remove a PRODUCT refId from an asset (no-op if absent). */\n async detachFromProduct(\n assetId: string,\n productId: string,\n auth: AuthContext = SERVICE,\n ): Promise<Asset> {\n const a = await this.get(assetId, auth);\n const refIds: AssetRefId[] = a.refIds ?? [];\n const next = refIds.filter((r) => !isProductRef(r, productId));\n if (next.length === refIds.length) return a;\n const patch = { type: a.type, refIds: next } as unknown as AssetUpdateInput;\n return this.update(assetId, { kind: \"json\", body: patch }, auth);\n }\n\n /** Convenience: list assets attached to a product (server-side filter). */\n async listForProduct(\n productId: string,\n auth: AuthContext = SERVICE,\n ): Promise<PaginatedItems<Asset>> {\n return this.list({ \"refIds.id\": productId }, auth);\n }\n}\n\n// Re-export so consumers can `import { isProductRef } from \"@viu/emporix-sdk/media\"`?\n// Internal helper — kept module-private; convenience methods in Task 4 use it.\nexport const _internalMedia = { isProductRef };\n"]}
1
+ {"version":3,"sources":["../src/core/paged.ts","../src/core/errors.ts","../src/services/media.ts"],"names":["text"],"mappings":";;;AAyBA,SAAS,SAAA,CAAU,SAAkB,IAAA,EAAkC;AACrE,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,IAAI,CAAA;AAC5B,EAAA,IAAI,QAAQ,IAAA,IAAQ,GAAA,CAAI,IAAA,EAAK,KAAM,IAAI,OAAO,MAAA;AAC9C,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,EAAA,OAAO,OAAO,SAAA,CAAU,CAAC,CAAA,IAAK,CAAA,IAAK,IAAI,CAAA,GAAI,MAAA;AAC7C;AAWA,eAAsB,WAAA,CACpB,IAAA,EACA,CAAA,EACA,IAAA,EAC4B;AAC5B,EAAA,MAAM,EAAE,IAAA,EAAM,OAAA,EAAQ,GAAI,MAAM,IAAA,CAAK,eAAA;AAAA,IACnC,KAAK,UAAA,KAAe,IAAA,GAChB,EAAE,GAAG,GAAG,OAAA,EAAS,EAAE,GAAI,CAAA,CAAE,WAAW,EAAC,EAAI,eAAA,EAAiB,MAAA,IAAS,GACnE;AAAA,GACN;AAIA,EAAA,MAAM,KAAA,GAAQ,QAAQ,EAAC;AACvB,EAAA,MAAM,UAAA,GAAa,SAAA,CAAU,OAAA,EAAS,eAAe,CAAA;AACrD,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,GAAA,CAAI,eAAe,CAAA,IAAK,MAAA;AACnD,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,GAAA,CAAI,eAAe,CAAA,IAAK,MAAA;AAKnD,EAAA,MAAM,WAAA,GACJ,UAAA,KAAe,MAAA,GACX,IAAA,GACA,UAAA,KAAe,MAAA,GACb,IAAA,CAAK,UAAA,GAAa,IAAA,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I,OAAgB,IAAA,EAAM,WAAA,EAAa,OAAO,GAAA,EAAI;AAC1D,IAAA,MAAM,KAAK,KAAA,CAAM,OAAA,EAAS,CAAC,EAAE,GAAG,IAAI,CAAA;AACpC,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,OAAA,EAAS,IAAI,CAAA;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,iBAAA,CACJ,OAAA,EACA,SAAA,EACA,OAAoB,OAAA,EACJ;AAChB,IAAA,MAAM,CAAA,GAAI,MAAM,IAAA,CAAK,GAAA,CAAI,SAAS,IAAI,CAAA;AACtC,IAAA,MAAM,MAAA,GAAuB,CAAA,CAAE,MAAA,IAAU,EAAC;AAC1C,IAAA,MAAM,IAAA,GAAO,OAAO,MAAA,CAAO,CAAC,MAAM,CAAC,YAAA,CAAa,CAAA,EAAG,SAAS,CAAC,CAAA;AAC7D,IAAA,IAAI,IAAA,CAAK,MAAA,KAAW,MAAA,CAAO,MAAA,EAAQ,OAAO,CAAA;AAC1C,IAAA,MAAM,IAAA,CAAK,KAAA,CAAM,OAAA,EAAS,CAAC,EAAE,EAAA,EAAI,SAAA,EAAW,IAAA,EAAM,SAAA,EAAW,KAAA,EAAO,IAAA,EAAM,GAAG,IAAI,CAAA;AACjF,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,OAAA,EAAS,IAAI,CAAA;AAAA,EAC/B;AAAA;AAAA,EAGA,MAAM,cAAA,CACJ,SAAA,EACA,IAAA,GAAoB,OAAA,EACY;AAChC,IAAA,OAAO,KAAK,IAAA,CAAK,EAAE,WAAA,EAAa,SAAA,IAAa,IAAI,CAAA;AAAA,EACnD;AACF;AAIO,IAAM,cAAA,GAAiB,EAAE,YAAA","file":"media.cjs","sourcesContent":["import type { PaginatedItems } from \"./context\";\nimport type { HttpClient, RequestOptions } from \"./http\";\n\n/** Pagination inputs for {@link requestPage}. */\nexport interface PageParams {\n /** 1-based, as Emporix counts. */\n pageNumber: number;\n pageSize: number;\n /**\n * Ask Emporix for the absolute match count via the `X-Total-Count: true`\n * request header.\n *\n * Off by default and opt-in per call, not a client-wide setting: the count\n * costs the server a second query, and defaulting it on would put that cost\n * on every list every storefront issues.\n */\n totalCount?: boolean;\n}\n\n/**\n * Reads a non-negative integer header, or `undefined` when it is missing or is\n * not one. A malformed value must not reach the `hasNextPage` arithmetic —\n * `Number(\"lots\")` is `NaN`, and every comparison against `NaN` is `false`,\n * which would silently report \"last page\" on every page.\n */\nfunction intHeader(headers: Headers, name: string): number | undefined {\n const raw = headers.get(name);\n if (raw === null || raw.trim() === \"\") return undefined;\n const n = Number(raw);\n return Number.isInteger(n) && n >= 0 ? n : undefined;\n}\n\n/**\n * Issues one page of a list endpoint and assembles {@link PaginatedItems} from\n * the body plus Emporix's pagination response headers.\n *\n * Cursors travel in opposite directions: the caller sends one as the `next` or\n * `prev` **query parameter** (so it belongs in `o.query`), and the server\n * returns the following one as the `X-Next-Cursor` **response header**. This\n * helper only ever reads them.\n */\nexport async function requestPage<T>(\n http: HttpClient,\n o: RequestOptions,\n page: PageParams,\n): Promise<PaginatedItems<T>> {\n const { data, headers } = await http.requestWithMeta<T[]>(\n page.totalCount === true\n ? { ...o, headers: { ...(o.headers ?? {}), \"X-Total-Count\": \"true\" } }\n : o,\n );\n\n // A 204 or empty body parses to `undefined`. Facades used to index straight\n // into the result and would throw; an empty page is the honest answer.\n const items = data ?? [];\n const totalCount = intHeader(headers, \"X-Total-Count\");\n const nextCursor = headers.get(\"X-Next-Cursor\") ?? undefined;\n const prevCursor = headers.get(\"X-Prev-Cursor\") ?? undefined;\n\n // Three tiers, most precise first. Tier 1 is ONE-DIRECTIONAL on purpose: only\n // two endpoints in the whole API emit a cursor header, so its absence says\n // nothing at all and has to fall through to the other two.\n const hasNextPage =\n nextCursor !== undefined\n ? true\n : totalCount !== undefined\n ? page.pageNumber * page.pageSize < totalCount\n : items.length === page.pageSize;\n\n // Spread conditionally — `exactOptionalPropertyTypes` rejects an explicit\n // `undefined` for an optional property.\n return {\n items,\n pageNumber: page.pageNumber,\n pageSize: page.pageSize,\n hasNextPage,\n ...(totalCount === undefined ? {} : { totalCount }),\n ...(nextCursor === undefined ? {} : { nextCursor }),\n ...(prevCursor === undefined ? {} : { prevCursor }),\n };\n}\n","/** Keys whose values are stripped from any serialised error body. */\nconst REDACTED_BODY_KEYS = new Set([\n \"access_token\", \"refresh_token\", \"token\", \"customertoken\", \"saastoken\",\n \"secret\", \"client_secret\", \"authorization\", \"password\",\n]);\n\nfunction scrub(body: unknown): unknown {\n if (Array.isArray(body)) return body.map(scrub);\n if (body && typeof body === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(body as Record<string, unknown>)) {\n out[k] = REDACTED_BODY_KEYS.has(k.toLowerCase()) ? \"***redacted***\" : scrub(v);\n }\n return out;\n }\n return body;\n}\n\n/** Base class for every error thrown by the SDK. */\nexport class EmporixError extends Error {\n readonly status: number | undefined;\n readonly body: unknown;\n constructor(message: string, status?: number, body?: unknown) {\n super(message);\n this.name = new.target.name;\n this.status = status;\n this.body = body;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n /** Safe serialisation — token-like body fields are redacted. */\n toJSON(): Record<string, unknown> {\n return { name: this.name, message: this.message, status: this.status, body: scrub(this.body) };\n }\n}\n\n/** 401 — authentication failed or token expired. */\nexport class EmporixAuthError extends EmporixError {}\n/** 403 — authenticated but not permitted. */\nexport class EmporixForbiddenError extends EmporixError {}\n/** 404 — resource not found. */\nexport class EmporixNotFoundError extends EmporixError {}\n/** 400/422 — request validation failed. */\nexport class EmporixValidationError extends EmporixError {}\n/** 5xx — server-side failure. */\nexport class EmporixServerError extends EmporixError {}\n/** Request aborted by the configured connect/read timeout. No HTTP status. */\nexport class EmporixTimeoutError extends EmporixError {}\n/** DNS/TLS/connection-level failure before or during the exchange. No HTTP status. */\nexport class EmporixNetworkError extends EmporixError {}\n\n/**\n * 403 with a `missing scope: <name>` hint in the body's `details` array.\n * Subclasses {@link EmporixForbiddenError} so existing 403 catches still work.\n */\nexport class EmporixInsufficientScopeError extends EmporixForbiddenError {\n readonly requiredScope: string | undefined;\n constructor(message: string, status: number, body: unknown, requiredScope?: string) {\n super(message, status, body);\n this.requiredScope = requiredScope;\n }\n}\n\nconst SCOPE_HINT_RE = /missing scope[: ]+([a-z0-9._-]+)/i;\n\nfunction extractRequiredScope(body: unknown): string | undefined {\n if (body && typeof body === \"object\" && \"details\" in body) {\n const details = (body as { details?: unknown }).details;\n if (Array.isArray(details)) {\n for (const d of details) {\n if (typeof d === \"string\") {\n const m = d.match(SCOPE_HINT_RE);\n if (m) return m[1];\n }\n }\n }\n }\n return undefined;\n}\n\n/** Maps an HTTP status to the matching {@link EmporixError} subclass. */\nexport function errorFromResponse(status: number, message: string, body: unknown): EmporixError {\n if (status === 401) return new EmporixAuthError(message, status, body);\n if (status === 403) {\n const scope = extractRequiredScope(body);\n if (scope) return new EmporixInsufficientScopeError(message, status, body, scope);\n return new EmporixForbiddenError(message, status, body);\n }\n if (status === 404) return new EmporixNotFoundError(message, status, body);\n if (status === 400 || status === 422) return new EmporixValidationError(message, status, body);\n if (status >= 500) return new EmporixServerError(message, status, body);\n return new EmporixError(message, status, body);\n}\n","import type { ClientContext, PaginatedItems } from \"../core/context\";\nimport { requestPage } from \"../core/paged\";\nimport type { AuthContext } from \"../core/auth\";\nimport { EmporixError, errorFromResponse } from \"../core/errors\";\nimport type {\n AssetCreateBlob,\n AssetCreateLink,\n AssetUpdateBlob,\n AssetUpdateLink,\n DownloadUrl,\n GetAsset,\n GetMediaRetrieveDownloadUrlData,\n MetadataUpdate,\n PatchOperation,\n RefId,\n UploadSession,\n UploadSessionRequest,\n} from \"../generated/media\";\n\n/**\n * The spec marks `metadata` optional on both update bodies; the live API rejects\n * an update without it — «`metadata.version` is required for update» (measured\n * 2026-10-06 on BLOB and LINK assets). Required here, so leaving it out is a\n * compile error rather than a 400.\n */\ntype Versioned<T> = Omit<T, \"metadata\"> & { metadata: MetadataUpdate };\n\n/** Generated media types (caller sends the exact wire shape). */\nexport type AssetCreateBlobInput = AssetCreateBlob;\nexport type AssetCreateLinkInput = AssetCreateLink;\nexport type AssetUpdateBlobInput = Versioned<AssetUpdateBlob>;\nexport type AssetUpdateLinkInput = Versioned<AssetUpdateLink>;\n/**\n * @deprecated `update()` takes {@link AssetUpdateLinkInput} as its JSON body and\n * {@link AssetUpdateBlobInput} next to a file; a BLOB is never sent as JSON.\n */\nexport type AssetUpdateInput = AssetUpdateBlob | AssetUpdateLink;\nexport type Asset = GetAsset;\nexport type AssetRefId = RefId;\n/** Partial-update body (`PATCH /assets/{id}`) — an RFC-6902 JSON-Patch op-array. */\nexport type AssetPatch = PatchOperation[];\n/** Result of {@link MediaService.getDownloadUrl} — `{ provider, url, expiresAt? }`. */\nexport type AssetDownloadUrl = DownloadUrl;\n/** Query for {@link MediaService.getDownloadUrl} — `{ disposition? }`. */\nexport type AssetDownloadUrlQuery = NonNullable<GetMediaRetrieveDownloadUrlData[\"query\"]>;\n/** Body for {@link MediaService.startUploadSession}: a BLOB create payload plus `uploadType`. */\nexport type AssetUploadSessionInput = UploadSessionRequest;\n/** The storage instruction {@link MediaService.startUploadSession} returns. */\nexport type AssetUploadSession = UploadSession;\n\n/**\n * Filter / pagination options for {@link MediaService.list}. The explicit\n * fields are typed for autocomplete; the index signature stays open so\n * Emporix `q`-syntax filters like `\"refIds.id\"` can be passed verbatim.\n */\nexport interface ListAssetsQuery {\n pageNumber?: number;\n pageSize?: number;\n /** Emporix sort syntax, e.g. `\"name,metadata.createdAt:desc\"`. */\n sort?: string;\n /** Emporix `q`-syntax filter, e.g. `\"name:hero\"`. */\n q?: string;\n /**\n * Ask for `X-Total-Count`. An SDK-side flag, not an Emporix query parameter:\n * it becomes a request header.\n */\n totalCount?: boolean;\n [key: string]: string | number | boolean | undefined;\n}\n\n/**\n * Result of {@link MediaService.download}. The endpoint's behaviour depends\n * on the asset's `access`:\n * - `PUBLIC` assets respond with a 30x redirect whose `Location` header\n * carries the externally-cacheable storage URL — useful when the\n * storefront wants to send the user there directly.\n * - `PRIVATE` assets respond with the raw bytes (plus an `ETag` header\n * for caching). The file lives in Google Cloud Storage and is reachable\n * without the service token only through a signed URL from\n * {@link MediaService.getDownloadUrl}.\n */\nexport type DownloadResult =\n | { kind: \"redirect\"; url: string }\n | {\n kind: \"bytes\";\n data: ArrayBuffer;\n etag?: string;\n contentType?: string;\n };\n\nconst SERVICE: AuthContext = { kind: \"service\" };\n\nfunction isProductRef(r: AssetRefId, productId: string): boolean {\n return r.type === \"PRODUCT\" && r.id === productId;\n}\n\n/**\n * Media assets (BLOB/LINK). All endpoints require a backend-only scope\n * (`media.asset_manage` / `media.asset_read`) — default auth: service.\n */\nexport class MediaService {\n static readonly channel = \"media\" as const;\n constructor(private readonly ctx: ClientContext) {}\n\n private base(): string {\n return `/media/${this.ctx.tenant}/assets`;\n }\n\n /**\n * Create an asset. BLOB uploads via multipart (max 30 MB); LINK via JSON.\n * {@link startUploadSession} sends the file straight to storage instead.\n */\n async create(\n input:\n | { kind: \"blob\"; file: Blob; body: AssetCreateBlobInput }\n | { kind: \"link\"; body: AssetCreateLinkInput },\n auth: AuthContext = SERVICE,\n ): Promise<{ id: string }> {\n if (input.kind === \"blob\") {\n const fd = new FormData();\n fd.set(\"file\", input.file);\n fd.set(\"body\", JSON.stringify(input.body));\n return this.ctx.http.request<{ id: string }>({\n method: \"POST\",\n path: this.base(),\n auth,\n body: fd,\n });\n }\n return this.ctx.http.request<{ id: string }>({\n method: \"POST\",\n path: this.base(),\n auth,\n body: input.body,\n });\n }\n\n /**\n * List assets, wrapped in the shared {@link PaginatedItems} envelope so\n * callers can iterate over pages consistently with the rest of the SDK.\n * `hasNextPage` is the standard SDK heuristic: `true` when the returned\n * page is full (`items.length === requested pageSize`). Pagination\n * defaults match Emporix's server defaults (`pageNumber: 1`,\n * `pageSize: 60`) so an empty `query` produces stable expectations.\n */\n async list(\n query: ListAssetsQuery = {},\n auth: AuthContext = SERVICE,\n ): Promise<PaginatedItems<Asset>> {\n const pageNumber = query.pageNumber ?? 1;\n const pageSize = query.pageSize ?? 60;\n // Destructured out because the rest of `query` is spread into the query\n // string: `totalCount` is an SDK-side flag that becomes a request header,\n // and would otherwise ride along as a stray `?totalCount=true`.\n const { totalCount, ...rest } = query;\n return requestPage<Asset>(\n this.ctx.http,\n {\n method: \"GET\",\n path: this.base(),\n auth,\n query: { ...rest, pageNumber, pageSize },\n },\n { pageNumber, pageSize, ...(totalCount === undefined ? {} : { totalCount }) },\n );\n }\n\n /** Fetch an asset by id. */\n async get(assetId: string, auth: AuthContext = SERVICE): Promise<Asset> {\n return this.ctx.http.request<Asset>({\n method: \"GET\",\n path: `${this.base()}/${assetId}`,\n auth,\n });\n }\n\n /**\n * Replace an asset (`PUT`, HTTP 204 — nothing is returned). The spec takes one\n * body per asset type, mirrored by the discriminated input:\n * - `{ kind: \"json\", body }` — a LINK asset, sent as `application/json`. The\n * body is the whole asset: `type: \"LINK\"`, `access` and `url` are required.\n * - `{ kind: \"blob\", file, body }` — a BLOB asset, sent as\n * `multipart/form-data`: the file (max 30 MB) and the asset body, both\n * required, so this always replaces the bytes.\n *\n * A BLOB's metadata alone — `refIds`, `details`, mixins — goes through\n * {@link patch}. Earlier versions also took a BLOB as the JSON body and\n * promised the updated asset in return; the spec allows neither.\n *\n * `type` and `access` are immutable. Optimistic locking is via\n * `body.metadata.version`; a stale one gets a 409.\n */\n async update(\n assetId: string,\n input:\n | { kind: \"json\"; body: AssetUpdateLinkInput }\n | { kind: \"blob\"; file: Blob; body: AssetUpdateBlobInput },\n auth: AuthContext = SERVICE,\n ): Promise<void> {\n const path = `${this.base()}/${encodeURIComponent(assetId)}`;\n if (input.kind === \"blob\") {\n const fd = new FormData();\n fd.set(\"file\", input.file);\n fd.set(\"body\", JSON.stringify(input.body));\n await this.ctx.http.request<void>({ method: \"PUT\", path, auth, body: fd });\n return;\n }\n await this.ctx.http.request<void>({ method: \"PUT\", path, auth, body: input.body });\n }\n\n /**\n * Partially update an asset with an RFC-6902 JSON-Patch op-array\n * (`PATCH /assets/{id}`, HTTP 204 — nothing is returned).\n *\n * This is the way to change one field without resending the whole asset, and\n * the only way to touch a `BLOB` asset's metadata **without re-uploading the\n * file** — {@link update} in `blob` mode always replaces the bytes.\n *\n * Append to an array with a path ending in `/-`, which preserves the existing\n * entries:\n *\n * ```ts\n * await client.media.patch(assetId, [\n * { op: \"add\", path: \"/refIds/-\", value: { id: \"product1\", type: \"PRODUCT\" } },\n * ]);\n * ```\n *\n * `type` and `access` are immutable here too, as with {@link update}. Only\n * `add`, `remove` and `replace` are accepted, and optimistic locking still\n * applies — a stale `metadata.version` gets a 409.\n */\n async patch(assetId: string, ops: AssetPatch, auth: AuthContext = SERVICE): Promise<void> {\n await this.ctx.http.request<void>({\n method: \"PATCH\",\n path: `${this.base()}/${encodeURIComponent(assetId)}`,\n auth,\n body: ops,\n });\n }\n\n /** Remove an asset. */\n async remove(assetId: string, auth: AuthContext = SERVICE): Promise<void> {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `${this.base()}/${assetId}`,\n auth,\n });\n }\n\n /**\n * Download an asset by id. Returns a discriminated union:\n * - `{ kind: \"redirect\", url }` for `PUBLIC` assets (server-side 30x with\n * the storage URL in `Location`).\n * - `{ kind: \"bytes\", data }` for `PRIVATE` assets (server-side 200 with\n * the asset bytes; `etag` + `contentType` headers are exposed for\n * caching). When the server reports `text/plain` Content-Type (the\n * OpenAPI-documented format), the SDK decodes the base64 stream into\n * an `ArrayBuffer` transparently; binary Content-Types are passed\n * through verbatim.\n *\n * Emporix recommends {@link getDownloadUrl} for every download: here the file\n * passes through the Media API. A `413` means the asset's known size exceeds\n * the streaming limit (30 MB by default) — only {@link getDownloadUrl} can\n * serve it. A `409` means the asset is still `PENDING` from a direct upload\n * whose file has not reached storage.\n *\n * Implementation note: uses `redirect: \"manual\"` so the redirect-location\n * is observable. In Node.js this works; in a browser the redirect Location\n * is intentionally hidden by fetch — there, `PUBLIC` downloads will\n * surface as an opaque-redirect and the SDK throws. Browser code should\n * use the asset's `url` field from `get()` for `LINK` assets, or the\n * direct storage URL for `PUBLIC` `BLOB` assets (typically delivered via\n * an `<img>` tag rather than `download()`).\n */\n async download(\n assetId: string,\n auth: AuthContext = SERVICE,\n ): Promise<DownloadResult> {\n const path = `${this.base()}/${assetId}/download`;\n const res = await this.ctx.http.requestRaw(\n { method: \"GET\", path, auth },\n { redirect: \"manual\" },\n );\n\n // PUBLIC: server-side redirect — capture Location.\n if (res.status >= 300 && res.status < 400) {\n const url = res.headers.get(\"location\");\n if (!url) {\n throw new EmporixError(\n `media.download: ${res.status} response without a Location header`,\n res.status,\n );\n }\n return { kind: \"redirect\", url };\n }\n\n // PRIVATE: bytes.\n if (res.ok) {\n const etag = res.headers.get(\"etag\") ?? undefined;\n const contentType = res.headers.get(\"content-type\") ?? undefined;\n let data: ArrayBuffer;\n if (contentType?.startsWith(\"text/plain\")) {\n // Per OpenAPI spec the server returns the byte stream as a\n // base64-encoded text/plain body. Decode once into raw bytes\n // so callers always see an ArrayBuffer.\n const text = await res.text();\n const bin = atob(text);\n const arr = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);\n data = arr.buffer;\n } else {\n data = await res.arrayBuffer();\n }\n return {\n kind: \"bytes\",\n data,\n ...(etag !== undefined ? { etag } : {}),\n ...(contentType !== undefined ? { contentType } : {}),\n };\n }\n\n // Error: surface via the standard EmporixError hierarchy.\n const text = await res.text();\n let parsed: unknown = undefined;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = text;\n }\n }\n throw errorFromResponse(res.status, `GET ${path} → ${res.status}`, parsed);\n }\n\n /**\n * Get a URL that serves the stored file straight from storage\n * (`GET /assets/{assetId}/download-url`). Emporix recommends it for every\n * download: the file never passes through the Media API, there is no size\n * limit, and the URL can be handed to a browser as it is.\n *\n * - `PRIVATE` BLOB → `provider: \"GCS\"`, a signed Google Cloud Storage URL that\n * works without an Emporix token until `expiresAt` (15 minutes by default).\n * - `PUBLIC` BLOB → `provider: \"CLOUDINARY\"`, the permanent URL.\n * - `LINK` → `provider: \"LINK\"`, the stored URL.\n *\n * `disposition` (`attachment` by default, or `inline`) affects private URLs\n * only. Unlike {@link startUploadSession}, this works whether or not direct\n * upload is enabled for the tenant. A `409` means a direct upload is still\n * `PENDING` and its file has not reached storage; once it has, this call\n * completes the asset before answering.\n */\n async getDownloadUrl(\n assetId: string,\n query: AssetDownloadUrlQuery = {},\n auth: AuthContext = SERVICE,\n ): Promise<AssetDownloadUrl> {\n return this.ctx.http.request<AssetDownloadUrl>({\n method: \"GET\",\n path: `${this.base()}/${encodeURIComponent(assetId)}/download-url`,\n auth,\n query: { ...query },\n });\n }\n\n /**\n * Start a direct upload of a `BLOB` asset (`POST /assets/upload-session`,\n * `201`). Emporix creates the asset as `PENDING` — `id` is its id — and\n * returns where to send the file. **This method does not send it**:\n *\n * - `upload.method === \"PUT\"` (a `PRIVATE` asset, `uploadType: \"put\"` or\n * omitted): `PUT` the file to `upload.url` with every `upload.headers` entry.\n * - `upload.method === \"POST\"` (every `PUBLIC` asset, or `uploadType: \"form\"`):\n * a multipart `POST` to `upload.url` with every `upload.fields` entry\n * unchanged and the file part last.\n *\n * That request goes to Google Cloud Storage or Cloudinary, not to Emporix, so\n * it must not carry the Emporix token — which is also why a browser can make\n * it. The asset turns `READY` once storage confirms; until then, calls that\n * need the file answer `409`. The instruction is valid for 15 minutes (GCS) or\n * an hour (Cloudinary), and an unused session expires at `expiresAt`.\n *\n * Direct upload is enabled per tenant by Emporix Support. Without it the call\n * throws an `EmporixForbiddenError` whose `body.message` is `direct upload is\n * not enabled for this tenant`, and nothing is created — the same status as a\n * missing scope, so read the message.\n */\n async startUploadSession(\n input: AssetUploadSessionInput,\n auth: AuthContext = SERVICE,\n ): Promise<AssetUploadSession> {\n return this.ctx.http.request<AssetUploadSession>({\n method: \"POST\",\n path: `${this.base()}/upload-session`,\n auth,\n body: input,\n });\n }\n\n /** Multipart upload sugar: builds `AssetCreateBlob` from input. */\n async uploadFile(\n input: {\n file: Blob;\n productId?: string;\n filename?: string;\n mimeType?: string;\n access?: \"PUBLIC\" | \"PRIVATE\";\n },\n auth: AuthContext = SERVICE,\n ): Promise<{ id: string }> {\n const body: AssetCreateBlobInput = {\n type: \"BLOB\",\n access: input.access ?? \"PUBLIC\",\n ...(input.productId\n ? { refIds: [{ type: \"PRODUCT\", id: input.productId }] }\n : {}),\n ...(input.filename || input.mimeType\n ? {\n details: {\n ...(input.filename ? { filename: input.filename } : {}),\n ...(input.mimeType ? { mimeType: input.mimeType } : {}),\n },\n }\n : {}),\n };\n return this.create({ kind: \"blob\", file: input.file, body }, auth);\n }\n\n /**\n * Replace the file content of an existing BLOB asset. Sugar over\n * {@link update} with `kind: \"blob\"`, and like it resolves to nothing — the\n * PUT answers 204. `access` is required because the field is immutable and\n * the server validates that the body matches.\n *\n * Pass `version` from `asset.metadata.version` for optimistic locking\n * (recommended when concurrent writers are possible) — a stale one gets a 409.\n * Without it the current version is read first, because the live API rejects\n * an update that carries none; the write then wins over any in between.\n */\n async replaceFile(\n assetId: string,\n input: {\n file: Blob;\n access: \"PUBLIC\" | \"PRIVATE\";\n filename?: string;\n mimeType?: string;\n version?: number;\n },\n auth: AuthContext = SERVICE,\n ): Promise<void> {\n const version =\n input.version ?? (await this.get(assetId, auth)).metadata?.version ?? 1;\n const body: AssetUpdateBlobInput = {\n type: \"BLOB\",\n access: input.access,\n ...(input.filename || input.mimeType\n ? {\n details: {\n ...(input.filename ? { filename: input.filename } : {}),\n ...(input.mimeType ? { mimeType: input.mimeType } : {}),\n },\n }\n : {}),\n metadata: { version },\n };\n return this.update(assetId, { kind: \"blob\", file: input.file, body }, auth);\n }\n\n /** External-URL sugar: builds `AssetCreateLink`. */\n async link(\n input: { url: string; productId?: string; access?: \"PUBLIC\" | \"PRIVATE\" },\n auth: AuthContext = SERVICE,\n ): Promise<{ id: string }> {\n const body: AssetCreateLinkInput = {\n type: \"LINK\",\n access: input.access ?? \"PUBLIC\",\n url: input.url,\n ...(input.productId\n ? { refIds: [{ type: \"PRODUCT\", id: input.productId }] }\n : {}),\n };\n return this.create({ kind: \"link\", body }, auth);\n }\n\n /**\n * Idempotently add a PRODUCT refId to an asset, through a JSON Patch that\n * appends the one reference, so it works for BLOB and LINK alike and leaves\n * the rest of the asset alone.\n *\n * Resolves to the asset as read back after the patch, because Emporix answers\n * 204 to a reference to a product that does not exist and drops it — check\n * `refIds` rather than trusting the call. Only a PUBLIC asset takes a product\n * reference; a PRIVATE one answers 400.\n *\n * Earlier versions sent a JSON PUT of `{ type, refIds }`, which the spec\n * rejects for both types: a BLOB takes no JSON PUT, and a LINK's requires\n * `access` and `url`.\n */\n async attachToProduct(\n assetId: string,\n productId: string,\n auth: AuthContext = SERVICE,\n ): Promise<Asset> {\n const a = await this.get(assetId, auth);\n const refIds: AssetRefId[] = a.refIds ?? [];\n if (refIds.some((r) => isProductRef(r, productId))) return a;\n const ref: AssetRefId = { type: \"PRODUCT\", id: productId };\n // `/refIds/-` appends to an existing array only (RFC 6902).\n const op =\n a.refIds === undefined\n ? { op: \"add\" as const, path: \"/refIds\", value: [ref] }\n : { op: \"add\" as const, path: \"/refIds/-\", value: ref };\n await this.patch(assetId, [op], auth);\n return this.get(assetId, auth);\n }\n\n /**\n * Remove a PRODUCT refId from an asset (no-op if absent), through a JSON Patch\n * that replaces the references and nothing else. Resolves to the asset as\n * read back after the patch, like {@link attachToProduct}. Earlier versions\n * sent a spec-invalid JSON PUT, as that one did.\n */\n async detachFromProduct(\n assetId: string,\n productId: string,\n auth: AuthContext = SERVICE,\n ): Promise<Asset> {\n const a = await this.get(assetId, auth);\n const refIds: AssetRefId[] = a.refIds ?? [];\n const next = refIds.filter((r) => !isProductRef(r, productId));\n if (next.length === refIds.length) return a;\n await this.patch(assetId, [{ op: \"replace\", path: \"/refIds\", value: next }], auth);\n return this.get(assetId, auth);\n }\n\n /** Convenience: list assets attached to a product (server-side filter). */\n async listForProduct(\n productId: string,\n auth: AuthContext = SERVICE,\n ): Promise<PaginatedItems<Asset>> {\n return this.list({ \"refIds.id\": productId }, auth);\n }\n}\n\n// Re-export so consumers can `import { isProductRef } from \"@viu/emporix-sdk/media\"`?\n// Internal helper — kept module-private; convenience methods in Task 4 use it.\nexport const _internalMedia = { isProductRef };\n"]}
package/dist/media.d.cts CHANGED
@@ -330,11 +330,24 @@ type GetMediaRetrieveDownloadUrlData = {
330
330
  url: '/media/{tenant}/assets/{assetId}/download-url';
331
331
  };
332
332
 
333
+ /**
334
+ * The spec marks `metadata` optional on both update bodies; the live API rejects
335
+ * an update without it — «`metadata.version` is required for update» (measured
336
+ * 2026-10-06 on BLOB and LINK assets). Required here, so leaving it out is a
337
+ * compile error rather than a 400.
338
+ */
339
+ type Versioned<T> = Omit<T, "metadata"> & {
340
+ metadata: MetadataUpdate;
341
+ };
333
342
  /** Generated media types (caller sends the exact wire shape). */
334
343
  type AssetCreateBlobInput = AssetCreateBlob;
335
344
  type AssetCreateLinkInput = AssetCreateLink;
336
- type AssetUpdateBlobInput = AssetUpdateBlob;
337
- type AssetUpdateLinkInput = AssetUpdateLink;
345
+ type AssetUpdateBlobInput = Versioned<AssetUpdateBlob>;
346
+ type AssetUpdateLinkInput = Versioned<AssetUpdateLink>;
347
+ /**
348
+ * @deprecated `update()` takes {@link AssetUpdateLinkInput} as its JSON body and
349
+ * {@link AssetUpdateBlobInput} next to a file; a BLOB is never sent as JSON.
350
+ */
338
351
  type AssetUpdateInput = AssetUpdateBlob | AssetUpdateLink;
339
352
  type Asset = GetAsset;
340
353
  type AssetRefId = RefId;
@@ -423,27 +436,29 @@ declare class MediaService {
423
436
  /** Fetch an asset by id. */
424
437
  get(assetId: string, auth?: AuthContext): Promise<Asset>;
425
438
  /**
426
- * Update an asset. The input is a discriminated union mirroring
427
- * {@link create}:
428
- * - `{ kind: "json", body }` — metadata-only patch (BLOB or LINK).
429
- * Sends `application/json`. Used for `refIds`, `details`, `metadata`,
430
- * or `url` changes.
431
- * - `{ kind: "blob", file, body }` — replaces the BLOB file content
432
- * (max 30 MB) AND patches metadata in the same request. Sends
433
- * `multipart/form-data`.
439
+ * Replace an asset (`PUT`, HTTP 204 — nothing is returned). The spec takes one
440
+ * body per asset type, mirrored by the discriminated input:
441
+ * - `{ kind: "json", body }` — a LINK asset, sent as `application/json`. The
442
+ * body is the whole asset: `type: "LINK"`, `access` and `url` are required.
443
+ * - `{ kind: "blob", file, body }` — a BLOB asset, sent as
444
+ * `multipart/form-data`: the file (max 30 MB) and the asset body, both
445
+ * required, so this always replaces the bytes.
446
+ *
447
+ * A BLOB's metadata alone — `refIds`, `details`, mixins — goes through
448
+ * {@link patch}. Earlier versions also took a BLOB as the JSON body and
449
+ * promised the updated asset in return; the spec allows neither.
434
450
  *
435
- * `type` and `access` are immutable per Emporix — they must match the
436
- * existing asset's values. Optimistic-locking is via `body.metadata.version`;
437
- * the server returns 409 Conflict on a stale version.
451
+ * `type` and `access` are immutable. Optimistic locking is via
452
+ * `body.metadata.version`; a stale one gets a 409.
438
453
  */
439
454
  update(assetId: string, input: {
440
455
  kind: "json";
441
- body: AssetUpdateInput;
456
+ body: AssetUpdateLinkInput;
442
457
  } | {
443
458
  kind: "blob";
444
459
  file: Blob;
445
460
  body: AssetUpdateBlobInput;
446
- }, auth?: AuthContext): Promise<Asset>;
461
+ }, auth?: AuthContext): Promise<void>;
447
462
  /**
448
463
  * Partially update an asset with an RFC-6902 JSON-Patch op-array
449
464
  * (`PATCH /assets/{id}`, HTTP 204 — nothing is returned).
@@ -547,10 +562,14 @@ declare class MediaService {
547
562
  }>;
548
563
  /**
549
564
  * Replace the file content of an existing BLOB asset. Sugar over
550
- * {@link update} with `kind: "blob"`. `access` is required because the
551
- * field is immutable and the server validates that the patch matches.
552
- * Pass `version` from `asset.metadata.version` if you want optimistic
553
- * locking (recommended when concurrent writers are possible).
565
+ * {@link update} with `kind: "blob"`, and like it resolves to nothing — the
566
+ * PUT answers 204. `access` is required because the field is immutable and
567
+ * the server validates that the body matches.
568
+ *
569
+ * Pass `version` from `asset.metadata.version` for optimistic locking
570
+ * (recommended when concurrent writers are possible) — a stale one gets a 409.
571
+ * Without it the current version is read first, because the live API rejects
572
+ * an update that carries none; the write then wins over any in between.
554
573
  */
555
574
  replaceFile(assetId: string, input: {
556
575
  file: Blob;
@@ -558,7 +577,7 @@ declare class MediaService {
558
577
  filename?: string;
559
578
  mimeType?: string;
560
579
  version?: number;
561
- }, auth?: AuthContext): Promise<Asset>;
580
+ }, auth?: AuthContext): Promise<void>;
562
581
  /** External-URL sugar: builds `AssetCreateLink`. */
563
582
  link(input: {
564
583
  url: string;
@@ -567,9 +586,27 @@ declare class MediaService {
567
586
  }, auth?: AuthContext): Promise<{
568
587
  id: string;
569
588
  }>;
570
- /** Idempotently add a PRODUCT refId to an asset. */
589
+ /**
590
+ * Idempotently add a PRODUCT refId to an asset, through a JSON Patch that
591
+ * appends the one reference, so it works for BLOB and LINK alike and leaves
592
+ * the rest of the asset alone.
593
+ *
594
+ * Resolves to the asset as read back after the patch, because Emporix answers
595
+ * 204 to a reference to a product that does not exist and drops it — check
596
+ * `refIds` rather than trusting the call. Only a PUBLIC asset takes a product
597
+ * reference; a PRIVATE one answers 400.
598
+ *
599
+ * Earlier versions sent a JSON PUT of `{ type, refIds }`, which the spec
600
+ * rejects for both types: a BLOB takes no JSON PUT, and a LINK's requires
601
+ * `access` and `url`.
602
+ */
571
603
  attachToProduct(assetId: string, productId: string, auth?: AuthContext): Promise<Asset>;
572
- /** Remove a PRODUCT refId from an asset (no-op if absent). */
604
+ /**
605
+ * Remove a PRODUCT refId from an asset (no-op if absent), through a JSON Patch
606
+ * that replaces the references and nothing else. Resolves to the asset as
607
+ * read back after the patch, like {@link attachToProduct}. Earlier versions
608
+ * sent a spec-invalid JSON PUT, as that one did.
609
+ */
573
610
  detachFromProduct(assetId: string, productId: string, auth?: AuthContext): Promise<Asset>;
574
611
  /** Convenience: list assets attached to a product (server-side filter). */
575
612
  listForProduct(productId: string, auth?: AuthContext): Promise<PaginatedItems<Asset>>;
package/dist/media.d.ts CHANGED
@@ -330,11 +330,24 @@ type GetMediaRetrieveDownloadUrlData = {
330
330
  url: '/media/{tenant}/assets/{assetId}/download-url';
331
331
  };
332
332
 
333
+ /**
334
+ * The spec marks `metadata` optional on both update bodies; the live API rejects
335
+ * an update without it — «`metadata.version` is required for update» (measured
336
+ * 2026-10-06 on BLOB and LINK assets). Required here, so leaving it out is a
337
+ * compile error rather than a 400.
338
+ */
339
+ type Versioned<T> = Omit<T, "metadata"> & {
340
+ metadata: MetadataUpdate;
341
+ };
333
342
  /** Generated media types (caller sends the exact wire shape). */
334
343
  type AssetCreateBlobInput = AssetCreateBlob;
335
344
  type AssetCreateLinkInput = AssetCreateLink;
336
- type AssetUpdateBlobInput = AssetUpdateBlob;
337
- type AssetUpdateLinkInput = AssetUpdateLink;
345
+ type AssetUpdateBlobInput = Versioned<AssetUpdateBlob>;
346
+ type AssetUpdateLinkInput = Versioned<AssetUpdateLink>;
347
+ /**
348
+ * @deprecated `update()` takes {@link AssetUpdateLinkInput} as its JSON body and
349
+ * {@link AssetUpdateBlobInput} next to a file; a BLOB is never sent as JSON.
350
+ */
338
351
  type AssetUpdateInput = AssetUpdateBlob | AssetUpdateLink;
339
352
  type Asset = GetAsset;
340
353
  type AssetRefId = RefId;
@@ -423,27 +436,29 @@ declare class MediaService {
423
436
  /** Fetch an asset by id. */
424
437
  get(assetId: string, auth?: AuthContext): Promise<Asset>;
425
438
  /**
426
- * Update an asset. The input is a discriminated union mirroring
427
- * {@link create}:
428
- * - `{ kind: "json", body }` — metadata-only patch (BLOB or LINK).
429
- * Sends `application/json`. Used for `refIds`, `details`, `metadata`,
430
- * or `url` changes.
431
- * - `{ kind: "blob", file, body }` — replaces the BLOB file content
432
- * (max 30 MB) AND patches metadata in the same request. Sends
433
- * `multipart/form-data`.
439
+ * Replace an asset (`PUT`, HTTP 204 — nothing is returned). The spec takes one
440
+ * body per asset type, mirrored by the discriminated input:
441
+ * - `{ kind: "json", body }` — a LINK asset, sent as `application/json`. The
442
+ * body is the whole asset: `type: "LINK"`, `access` and `url` are required.
443
+ * - `{ kind: "blob", file, body }` — a BLOB asset, sent as
444
+ * `multipart/form-data`: the file (max 30 MB) and the asset body, both
445
+ * required, so this always replaces the bytes.
446
+ *
447
+ * A BLOB's metadata alone — `refIds`, `details`, mixins — goes through
448
+ * {@link patch}. Earlier versions also took a BLOB as the JSON body and
449
+ * promised the updated asset in return; the spec allows neither.
434
450
  *
435
- * `type` and `access` are immutable per Emporix — they must match the
436
- * existing asset's values. Optimistic-locking is via `body.metadata.version`;
437
- * the server returns 409 Conflict on a stale version.
451
+ * `type` and `access` are immutable. Optimistic locking is via
452
+ * `body.metadata.version`; a stale one gets a 409.
438
453
  */
439
454
  update(assetId: string, input: {
440
455
  kind: "json";
441
- body: AssetUpdateInput;
456
+ body: AssetUpdateLinkInput;
442
457
  } | {
443
458
  kind: "blob";
444
459
  file: Blob;
445
460
  body: AssetUpdateBlobInput;
446
- }, auth?: AuthContext): Promise<Asset>;
461
+ }, auth?: AuthContext): Promise<void>;
447
462
  /**
448
463
  * Partially update an asset with an RFC-6902 JSON-Patch op-array
449
464
  * (`PATCH /assets/{id}`, HTTP 204 — nothing is returned).
@@ -547,10 +562,14 @@ declare class MediaService {
547
562
  }>;
548
563
  /**
549
564
  * Replace the file content of an existing BLOB asset. Sugar over
550
- * {@link update} with `kind: "blob"`. `access` is required because the
551
- * field is immutable and the server validates that the patch matches.
552
- * Pass `version` from `asset.metadata.version` if you want optimistic
553
- * locking (recommended when concurrent writers are possible).
565
+ * {@link update} with `kind: "blob"`, and like it resolves to nothing — the
566
+ * PUT answers 204. `access` is required because the field is immutable and
567
+ * the server validates that the body matches.
568
+ *
569
+ * Pass `version` from `asset.metadata.version` for optimistic locking
570
+ * (recommended when concurrent writers are possible) — a stale one gets a 409.
571
+ * Without it the current version is read first, because the live API rejects
572
+ * an update that carries none; the write then wins over any in between.
554
573
  */
555
574
  replaceFile(assetId: string, input: {
556
575
  file: Blob;
@@ -558,7 +577,7 @@ declare class MediaService {
558
577
  filename?: string;
559
578
  mimeType?: string;
560
579
  version?: number;
561
- }, auth?: AuthContext): Promise<Asset>;
580
+ }, auth?: AuthContext): Promise<void>;
562
581
  /** External-URL sugar: builds `AssetCreateLink`. */
563
582
  link(input: {
564
583
  url: string;
@@ -567,9 +586,27 @@ declare class MediaService {
567
586
  }, auth?: AuthContext): Promise<{
568
587
  id: string;
569
588
  }>;
570
- /** Idempotently add a PRODUCT refId to an asset. */
589
+ /**
590
+ * Idempotently add a PRODUCT refId to an asset, through a JSON Patch that
591
+ * appends the one reference, so it works for BLOB and LINK alike and leaves
592
+ * the rest of the asset alone.
593
+ *
594
+ * Resolves to the asset as read back after the patch, because Emporix answers
595
+ * 204 to a reference to a product that does not exist and drops it — check
596
+ * `refIds` rather than trusting the call. Only a PUBLIC asset takes a product
597
+ * reference; a PRIVATE one answers 400.
598
+ *
599
+ * Earlier versions sent a JSON PUT of `{ type, refIds }`, which the spec
600
+ * rejects for both types: a BLOB takes no JSON PUT, and a LINK's requires
601
+ * `access` and `url`.
602
+ */
571
603
  attachToProduct(assetId: string, productId: string, auth?: AuthContext): Promise<Asset>;
572
- /** Remove a PRODUCT refId from an asset (no-op if absent). */
604
+ /**
605
+ * Remove a PRODUCT refId from an asset (no-op if absent), through a JSON Patch
606
+ * that replaces the references and nothing else. Resolves to the asset as
607
+ * read back after the patch, like {@link attachToProduct}. Earlier versions
608
+ * sent a spec-invalid JSON PUT, as that one did.
609
+ */
573
610
  detachFromProduct(assetId: string, productId: string, auth?: AuthContext): Promise<Asset>;
574
611
  /** Convenience: list assets attached to a product (server-side filter). */
575
612
  listForProduct(productId: string, auth?: AuthContext): Promise<PaginatedItems<Asset>>;
package/dist/media.js CHANGED
@@ -1,4 +1,4 @@
1
- export { MediaService, _internalMedia } from './chunk-5MPL4XBD.js';
1
+ export { MediaService, _internalMedia } from './chunk-NFSO7WUA.js';
2
2
  import './chunk-LKHKFF7B.js';
3
3
  import './chunk-UWGGF4MC.js';
4
4
  //# sourceMappingURL=media.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@viu/emporix-sdk",
3
- "version": "4.2.4",
3
+ "version": "4.3.0",
4
4
  "description": "TypeScript SDK for the Emporix Commerce Engine",
5
5
  "license": "MIT",
6
6
  "author": {