@embark-black-book/api-contract 0.3.0 → 0.5.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/README.md CHANGED
@@ -152,6 +152,80 @@ async function createCategory(baseUrl: string, token?: string) {
152
152
  }
153
153
  ```
154
154
 
155
+ ## Auth Refresh Helpers
156
+
157
+ Use dedicated auth helpers for local login, logout, and refresh flows.
158
+
159
+ ```ts
160
+ import {
161
+ authLocalJson,
162
+ authLogoutJson,
163
+ authRefreshJson,
164
+ type AuthRefreshResponse,
165
+ } from "@embark-black-book/api-contract";
166
+
167
+ async function refreshAuth(baseUrl: string, refreshToken: string) {
168
+ const parsed = await authRefreshJson({
169
+ baseUrl,
170
+ refreshToken,
171
+ });
172
+
173
+ const payload: AuthRefreshResponse | null = parsed.data;
174
+ return payload;
175
+ }
176
+ ```
177
+
178
+ `authRefreshJson` requires `refreshToken` (not access token) and throws `ApiResponseError` for non-2xx responses.
179
+
180
+ ## Refresh Utilities
181
+
182
+ Optional utilities are exported to help app-level refresh policy code stay consistent.
183
+
184
+ ```ts
185
+ import {
186
+ computeRefreshWindowDecision,
187
+ createSingleFlightRefresh,
188
+ } from "@embark-black-book/api-contract";
189
+
190
+ const refreshOnce = createSingleFlightRefresh(async (token: string) => {
191
+ return refreshAuth("http://localhost:1337/api", token);
192
+ });
193
+
194
+ const decision = computeRefreshWindowDecision({
195
+ expiresAtMs: Date.now() + 120_000,
196
+ refreshBeforeExpiryMs: 60_000,
197
+ });
198
+
199
+ if (decision.shouldRefresh) {
200
+ await refreshOnce("refresh-token-value");
201
+ }
202
+ ```
203
+
204
+ ## Strapi Image Helpers
205
+
206
+ Use shared image utilities to pick a deterministic format and resolve relative Strapi media URLs against the API origin.
207
+
208
+ ```ts
209
+ import {
210
+ getBestImageUrl,
211
+ type ApiMedia,
212
+ } from "@embark-black-book/api-contract";
213
+
214
+ function getCardImage(baseUrl: string, image: ApiMedia | null | undefined) {
215
+ return getBestImageUrl(baseUrl, image, 640);
216
+ }
217
+ ```
218
+
219
+ Format selection is deterministic and uses known Strapi image sizes:
220
+
221
+ - `xsmall`: `64`
222
+ - `small`: `500`
223
+ - `medium`: `750`
224
+ - `large`: `1000`
225
+ - `xlarge`: `1920`
226
+
227
+ The helper picks the smallest available format whose known size is greater than or equal to the requested render size. If no suitable format exists, or no formats are present, it falls back to the base image URL.
228
+
155
229
  ## Call Endpoint Without Token
156
230
 
157
231
  ```ts
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  AuthLocalResponse,
3
3
  AuthLogoutResponse,
4
+ AuthRefreshResponse,
4
5
  GeneratedApiClient,
5
6
  } from "./generated/api-client";
6
7
  import type { ParsedApiResponse } from "./api-response-helpers";
@@ -13,6 +14,14 @@ export type AuthLogoutRequestOptions = Parameters<
13
14
  GeneratedApiClient["createAuthLogout"]
14
15
  >[0];
15
16
 
17
+ export type AuthRefreshRequestOptions = Omit<
18
+ Parameters<GeneratedApiClient["createAuthRefresh"]>[0],
19
+ "token"
20
+ > & {
21
+ /** Refresh token used for /auth/refresh. */
22
+ refreshToken: string;
23
+ };
24
+
16
25
  export declare function authLocalJson(
17
26
  options: AuthLocalRequestOptions,
18
27
  client?: GeneratedApiClient
@@ -22,3 +31,8 @@ export declare function authLogoutJson(
22
31
  options: AuthLogoutRequestOptions,
23
32
  client?: GeneratedApiClient
24
33
  ): Promise<ParsedApiResponse<AuthLogoutResponse>>;
34
+
35
+ export declare function authRefreshJson(
36
+ options: AuthRefreshRequestOptions,
37
+ client?: GeneratedApiClient
38
+ ): Promise<ParsedApiResponse<AuthRefreshResponse>>;
@@ -18,7 +18,18 @@ async function authLogoutJson(options, client) {
18
18
  return parseApiResponse(response);
19
19
  }
20
20
 
21
+ async function authRefreshJson(options, client) {
22
+ const resolvedClient = client || apiClient;
23
+ const { refreshToken, ...rest } = options;
24
+ const response = await resolvedClient.createAuthRefresh({
25
+ ...rest,
26
+ token: refreshToken,
27
+ });
28
+ return requireApiResponseOk(response);
29
+ }
30
+
21
31
  module.exports = {
22
32
  authLocalJson,
23
33
  authLogoutJson,
34
+ authRefreshJson,
24
35
  };
@@ -0,0 +1,24 @@
1
+ export interface RefreshWindowOptions {
2
+ expiresAtMs: number;
3
+ nowMs?: number;
4
+ refreshBeforeExpiryMs?: number;
5
+ }
6
+
7
+ export interface RefreshWindowDecision {
8
+ shouldRefresh: boolean;
9
+ nowMs: number;
10
+ expiresAtMs: number;
11
+ refreshAtMs: number;
12
+ timeToExpiryMs: number;
13
+ }
14
+
15
+ export declare function computeRefreshWindowDecision(
16
+ options: RefreshWindowOptions
17
+ ): RefreshWindowDecision;
18
+
19
+ export declare function createSingleFlightRefresh<
20
+ TArgs extends unknown[],
21
+ TResult
22
+ >(
23
+ refreshFn: (...args: TArgs) => Promise<TResult>
24
+ ): (...args: TArgs) => Promise<TResult>;
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+
3
+ function computeRefreshWindowDecision(options) {
4
+ if (!options || typeof options !== "object") {
5
+ throw new Error("computeRefreshWindowDecision requires options.");
6
+ }
7
+
8
+ const expiresAtMs = Number(options.expiresAtMs);
9
+ if (!Number.isFinite(expiresAtMs)) {
10
+ throw new Error("expiresAtMs must be a finite number.");
11
+ }
12
+
13
+ const nowMs =
14
+ options.nowMs === undefined ? Date.now() : Number(options.nowMs);
15
+ if (!Number.isFinite(nowMs)) {
16
+ throw new Error("nowMs must be a finite number when provided.");
17
+ }
18
+
19
+ const refreshBeforeExpiryMs =
20
+ options.refreshBeforeExpiryMs === undefined
21
+ ? 60_000
22
+ : Number(options.refreshBeforeExpiryMs);
23
+ if (!Number.isFinite(refreshBeforeExpiryMs) || refreshBeforeExpiryMs < 0) {
24
+ throw new Error(
25
+ "refreshBeforeExpiryMs must be a finite number greater than or equal to 0."
26
+ );
27
+ }
28
+
29
+ const refreshAtMs = expiresAtMs - refreshBeforeExpiryMs;
30
+ const shouldRefresh = nowMs >= refreshAtMs;
31
+
32
+ return {
33
+ shouldRefresh,
34
+ nowMs,
35
+ expiresAtMs,
36
+ refreshAtMs,
37
+ timeToExpiryMs: expiresAtMs - nowMs,
38
+ };
39
+ }
40
+
41
+ function createSingleFlightRefresh(refreshFn) {
42
+ if (typeof refreshFn !== "function") {
43
+ throw new Error("createSingleFlightRefresh requires a function.");
44
+ }
45
+
46
+ let inFlight = null;
47
+
48
+ return function singleFlightRefresh(...args) {
49
+ if (!inFlight) {
50
+ inFlight = Promise.resolve()
51
+ .then(() => refreshFn(...args))
52
+ .finally(() => {
53
+ inFlight = null;
54
+ });
55
+ }
56
+
57
+ return inFlight;
58
+ };
59
+ }
60
+
61
+ module.exports = {
62
+ computeRefreshWindowDecision,
63
+ createSingleFlightRefresh,
64
+ };
@@ -45,6 +45,7 @@ export interface ApiParameters {
45
45
  export type AuthLocalRequest = { identifier: string; password: string; };
46
46
  export type AuthLocalResponse = { jwt: string; refreshToken?: string; user: { id: number; documentId: string; username: string; email: string; provider: string; confirmed: boolean; blocked: boolean; role?: number | { id: unknown; name: unknown; description: unknown; type: unknown; createdAt: unknown; updatedAt: unknown; }; createdAt: string; updatedAt: string; publishedAt: string; }; };
47
47
  export type AuthLogoutResponse = null;
48
+ export type AuthRefreshResponse = { jwt: string; refreshToken?: string; user: { id: number; documentId: string; username: string; email: string; provider: string; confirmed: boolean; blocked: boolean; role?: number | { id: unknown; name: unknown; description: unknown; type: unknown; createdAt: unknown; updatedAt: unknown; }; createdAt: string; updatedAt: string; publishedAt: string; }; };
48
49
 
49
50
  export type ApiClientDefinition = { name: string; group: string; method: string; pathTemplate: string; pathParams: string[]; hasBody: boolean; queryParams: string[] };
50
51
 
@@ -256,7 +257,8 @@ export interface GeneratedApiClient {
256
257
  }): Promise<Response>;
257
258
  createAuthRefresh(options: {
258
259
  baseUrl: string;
259
- token?: string;
260
+ /** Refresh token passed as Authorization: Bearer <token> for /auth/refresh. */
261
+ token: string;
260
262
  headers?: Record<string, string>;
261
263
  signal?: AbortSignal;
262
264
  fetchImpl?: typeof fetch;
@@ -16,7 +16,7 @@ export interface ApiMedia extends ApiBaseEntity<string | number> {
16
16
  focalPoint?: unknown;
17
17
  width?: number;
18
18
  height?: number;
19
- formats?: unknown;
19
+ formats?: StrapiImageFormats;
20
20
  hash: string;
21
21
  ext?: string;
22
22
  mime: string;
@@ -28,6 +28,33 @@ export interface ApiMedia extends ApiBaseEntity<string | number> {
28
28
  related: unknown;
29
29
  }
30
30
 
31
+ export type StrapiImageFormatName =
32
+ | "xsmall"
33
+ | "small"
34
+ | "medium"
35
+ | "large"
36
+ | "xlarge";
37
+
38
+ export interface StrapiImageFormat {
39
+ url: string;
40
+ width?: number;
41
+ height?: number;
42
+ size?: number;
43
+ ext?: string;
44
+ mime?: string;
45
+ hash?: string;
46
+ name?: string;
47
+ path?: string;
48
+ }
49
+
50
+ export interface StrapiImageFormats {
51
+ xsmall?: StrapiImageFormat;
52
+ small?: StrapiImageFormat;
53
+ medium?: StrapiImageFormat;
54
+ large?: StrapiImageFormat;
55
+ xlarge?: StrapiImageFormat;
56
+ }
57
+
31
58
  export interface ApiUsersPermissionsRole extends ApiBaseEntity<string | number> {
32
59
  name: string;
33
60
  description?: string;
package/dist/index.d.ts CHANGED
@@ -2,3 +2,5 @@ export * from './generated/api-types';
2
2
  export * from './generated/api-client';
3
3
  export * from './api-response-helpers';
4
4
  export * from './auth-helpers';
5
+ export * from './auth-refresh-utils';
6
+ export * from './strapi-image-helpers';
package/dist/index.js CHANGED
@@ -3,9 +3,13 @@
3
3
  const apiClient = require("./generated/api-client");
4
4
  const responseHelpers = require("./api-response-helpers");
5
5
  const authHelpers = require("./auth-helpers");
6
+ const authRefreshUtils = require("./auth-refresh-utils");
7
+ const strapiImageHelpers = require("./strapi-image-helpers");
6
8
 
7
9
  module.exports = {
8
10
  ...apiClient,
9
11
  ...responseHelpers,
10
12
  ...authHelpers,
13
+ ...authRefreshUtils,
14
+ ...strapiImageHelpers,
11
15
  };
@@ -0,0 +1,47 @@
1
+ export type StrapiImageFormatName =
2
+ | "xsmall"
3
+ | "small"
4
+ | "medium"
5
+ | "large"
6
+ | "xlarge";
7
+
8
+ export interface StrapiImageFormat {
9
+ url: string;
10
+ width?: number;
11
+ height?: number;
12
+ size?: number;
13
+ ext?: string;
14
+ mime?: string;
15
+ hash?: string;
16
+ name?: string;
17
+ path?: string;
18
+ }
19
+
20
+ export interface StrapiImageFormats {
21
+ xsmall?: StrapiImageFormat;
22
+ small?: StrapiImageFormat;
23
+ medium?: StrapiImageFormat;
24
+ large?: StrapiImageFormat;
25
+ xlarge?: StrapiImageFormat;
26
+ }
27
+
28
+ export interface StrapiImageLike {
29
+ url: string;
30
+ formats?: StrapiImageFormats | null;
31
+ }
32
+
33
+ export declare const STRAPI_IMAGE_FORMAT_WIDTHS: Readonly<
34
+ Record<StrapiImageFormatName, number>
35
+ >;
36
+
37
+ export declare function resolveStrapiAssetUrl(
38
+ baseUrl: string,
39
+ assetUrl?: string | null
40
+ ): string;
41
+
42
+ export declare function getBestImageUrl(
43
+ baseUrl: string,
44
+ image?: StrapiImageLike | null,
45
+ width?: number,
46
+ height?: number
47
+ ): string;
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+
3
+ const STRAPI_IMAGE_FORMAT_WIDTHS = Object.freeze({
4
+ xsmall: 64,
5
+ small: 500,
6
+ medium: 750,
7
+ large: 1000,
8
+ xlarge: 1920,
9
+ });
10
+
11
+ const STRAPI_IMAGE_FORMAT_ORDER = Object.freeze([
12
+ "xsmall",
13
+ "small",
14
+ "medium",
15
+ "large",
16
+ "xlarge",
17
+ ]);
18
+
19
+ function isAbsoluteUrl(value) {
20
+ try {
21
+ const parsed = new URL(value);
22
+ return Boolean(parsed.protocol && parsed.host);
23
+ } catch (_error) {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ function getApiOrigin(baseUrl) {
29
+ try {
30
+ const parsed = new URL(String(baseUrl || ""));
31
+ return parsed.origin;
32
+ } catch (_error) {
33
+ return "";
34
+ }
35
+ }
36
+
37
+ function normalizeAssetPath(assetUrl) {
38
+ const value = String(assetUrl || "").trim();
39
+ if (!value) {
40
+ return "";
41
+ }
42
+
43
+ if (value.startsWith("/")) {
44
+ return value;
45
+ }
46
+
47
+ return `/${value}`;
48
+ }
49
+
50
+ function resolveStrapiAssetUrl(baseUrl, assetUrl) {
51
+ const normalized = String(assetUrl || "").trim();
52
+ if (!normalized) {
53
+ return "";
54
+ }
55
+
56
+ if (isAbsoluteUrl(normalized)) {
57
+ return normalized;
58
+ }
59
+
60
+ const origin = getApiOrigin(baseUrl);
61
+ if (!origin) {
62
+ return normalized;
63
+ }
64
+
65
+ return new URL(normalizeAssetPath(normalized), origin).toString();
66
+ }
67
+
68
+ function normalizeRequestedRenderSize(width, height) {
69
+ const widthPx = Number(width);
70
+ const heightPx = height === undefined ? 0 : Number(height);
71
+
72
+ const safeWidth = Number.isFinite(widthPx) && widthPx > 0 ? widthPx : 0;
73
+ const safeHeight = Number.isFinite(heightPx) && heightPx > 0 ? heightPx : 0;
74
+
75
+ return Math.max(safeWidth, safeHeight);
76
+ }
77
+
78
+ function getKnownFormatEntries(image) {
79
+ if (!image || typeof image !== "object") {
80
+ return [];
81
+ }
82
+
83
+ const formats = image.formats;
84
+ if (!formats || typeof formats !== "object") {
85
+ return [];
86
+ }
87
+
88
+ const entries = [];
89
+ for (const formatName of STRAPI_IMAGE_FORMAT_ORDER) {
90
+ const format = formats[formatName];
91
+ if (!format || typeof format !== "object") {
92
+ continue;
93
+ }
94
+
95
+ if (typeof format.url !== "string" || format.url.trim() === "") {
96
+ continue;
97
+ }
98
+
99
+ entries.push({
100
+ name: formatName,
101
+ width: STRAPI_IMAGE_FORMAT_WIDTHS[formatName],
102
+ url: format.url,
103
+ });
104
+ }
105
+
106
+ return entries;
107
+ }
108
+
109
+ function getBestImageUrl(baseUrl, image, width, height) {
110
+ const baseImageUrl = image && typeof image.url === "string" ? image.url : "";
111
+ const requestedSize = normalizeRequestedRenderSize(width, height);
112
+ const formatEntries = getKnownFormatEntries(image);
113
+
114
+ if (requestedSize <= 0 || formatEntries.length === 0) {
115
+ return resolveStrapiAssetUrl(baseUrl, baseImageUrl);
116
+ }
117
+
118
+ const selected = formatEntries.find((entry) => entry.width >= requestedSize);
119
+ if (!selected) {
120
+ return resolveStrapiAssetUrl(baseUrl, baseImageUrl);
121
+ }
122
+
123
+ return resolveStrapiAssetUrl(baseUrl, selected.url);
124
+ }
125
+
126
+ module.exports = {
127
+ STRAPI_IMAGE_FORMAT_WIDTHS,
128
+ getBestImageUrl,
129
+ resolveStrapiAssetUrl,
130
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@embark-black-book/api-contract",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Type contract package generated from Blackbook by Embark Strapi OpenAPI",
5
5
  "license": "UNLICENSED",
6
6
  "exports": {
@@ -18,6 +18,7 @@
18
18
  "generate:client": "node ./scripts/generate-client.js",
19
19
  "generate:types": "node ./scripts/generate-types.js",
20
20
  "prepublishOnly": "npm run verify:publish",
21
+ "test:image-helpers": "node --test ./tests/strapi-image-helpers.test.js",
21
22
  "verify:publish": "node ./scripts/verify-package.js",
22
23
  "watch:types": "node ./scripts/watch-contract-types.js"
23
24
  },