drupal-canvas 0.7.1 → 0.8.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.
@@ -1,3 +1,619 @@
1
- import { _ as toBackendRelativePath, a as isDraftSessionError, c as JSONAPI_DRAFT_SESSION_EXPIRED_ERROR, d as isSafeProxyPath, f as mapJsonApiRequestToProxy, g as resolveJsonApiProxyPath, h as resolveJsonApiBase, i as createJsonApiClient, l as JSONAPI_PROXY_SESSION_EXPIRED, m as normalizeBaseUrl, n as DraftSessionError, o as DEFAULT_JSONAPI_PREFIX, p as mapProxyPathToUpstream, r as LegacyJsonApiClient, s as DEFAULT_ROUTER_PREFIX, t as CanvasJsonApiClient, u as JSONAPI_PROXY_SESSION_HEADER, v as trimSlashes } from "./jsonapi-client-CejP62bM.js";
1
+ import { r as assertLegacyRuntime } from "./migration-CxRMGzhm.js";
2
+ import { DefaultSerializer, JsonApiClient } from "@drupal-api-client/json-api-client";
2
3
  export * from "@drupal-api-client/json-api-client";
4
+ // src/jsonapi-proxy.ts
5
+ /**
6
+ * @file
7
+ * Framework-agnostic URL mapping between a Drupal backend's JSON:API
8
+ * endpoints and a same-origin application proxy. The browser client maps
9
+ * upstream URLs to the proxy; the proxy (in the Canvas Headless SDK) validates
10
+ * and maps them back. Both sides share this module so they cannot disagree
11
+ * about which paths are supported.
12
+ *
13
+ * The supported endpoints are those the JSON:API client reaches:
14
+ * - the JSON:API prefix (resources, collections, views, the index), and
15
+ * - the Decoupled Router path translation endpoint (`getResourceByPath()`).
16
+ * Both may be preceded by one Drupal language path prefix.
17
+ *
18
+ * @see docs/adr/0021-code-component-runtime-compatibility-across-frontend-modes.md
19
+ */
20
+ /** The default JSON:API prefix of Drupal core's JSON:API module. */
21
+ const DEFAULT_JSONAPI_PREFIX = "jsonapi";
22
+ /** The default path of the Decoupled Router module's endpoint. */
23
+ const DEFAULT_ROUTER_PREFIX = "router/translate-path";
24
+ /**
25
+ * The response header the proxy sets on draft-session errors, and the value
26
+ * it carries when the session expired or is invalid.
27
+ */
28
+ const JSONAPI_PROXY_SESSION_HEADER = "X-Canvas-Draft-Session";
29
+ const JSONAPI_PROXY_SESSION_EXPIRED = "expired";
30
+ /** The `error` code of the proxy's draft-session error body. */
31
+ const JSONAPI_DRAFT_SESSION_EXPIRED_ERROR = "draft_session_expired";
32
+ /**
33
+ * Resolves the JSON:API base and prefix. A full URL override under the
34
+ * backend base URL is a prefix override (a locale prefix goes between the
35
+ * site path and the prefix, as Drupal serves it); an override elsewhere is a
36
+ * foreign base whose path is the prefix.
37
+ */
38
+ function resolveJsonApiBase(baseUrl, endpoints = {}) {
39
+ const site = normalizeBaseUrl(baseUrl);
40
+ if (endpoints.apiUrl) {
41
+ const api = normalizeBaseUrl(endpoints.apiUrl);
42
+ if (api === site || api.startsWith(`${site}/`)) return {
43
+ base: site,
44
+ apiPrefix: trimSlashes(api.slice(site.length)) || "jsonapi",
45
+ foreign: false,
46
+ siteKnown: true
47
+ };
48
+ if (endpoints.apiSiteUrl) {
49
+ const apiSite = normalizeBaseUrl(endpoints.apiSiteUrl);
50
+ if (api !== apiSite && !api.startsWith(`${apiSite}/`)) throw new Error(`[drupal-canvas] The JSON:API URL (${api}) is not under its site base URL (${apiSite}).`);
51
+ return {
52
+ base: apiSite,
53
+ apiPrefix: trimSlashes(api.slice(apiSite.length)) || "jsonapi",
54
+ foreign: true,
55
+ siteKnown: true
56
+ };
57
+ }
58
+ const url = new URL(api);
59
+ return {
60
+ base: url.origin,
61
+ apiPrefix: trimSlashes(url.pathname) || "jsonapi",
62
+ foreign: true,
63
+ siteKnown: false
64
+ };
65
+ }
66
+ return {
67
+ base: site,
68
+ apiPrefix: trimSlashes(endpoints.apiPrefix || "jsonapi"),
69
+ foreign: false,
70
+ siteKnown: true
71
+ };
72
+ }
73
+ /**
74
+ * A possible language prefix is one safe path segment, not a language code.
75
+ * Drupal permits custom text (but no slash); this is not a configuration lookup.
76
+ * Reject ambiguous escapes and URL delimiters before allowing an extra segment
77
+ * in front of the configured endpoint. Never decode the forwarded path itself.
78
+ */
79
+ function isSafeOptionalPrefix(segment) {
80
+ try {
81
+ const decoded = decodeURIComponent(segment);
82
+ return decoded !== "." && decoded !== ".." && !/[/\\%?#\p{Cc}]/u.test(decoded);
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+ /** Strips surrounding slashes. */
88
+ function trimSlashes(value) {
89
+ return value.replace(/^\/+|\/+$/g, "");
90
+ }
91
+ function splitSegments(prefix) {
92
+ return trimSlashes(prefix).split("/").filter(Boolean);
93
+ }
94
+ /**
95
+ * Whether `path` is a safe site-relative path: one leading slash, no empty,
96
+ * dot, or dot-dot segments, no backslashes, and no encoded slashes that could
97
+ * decode into a different path upstream.
98
+ */
99
+ function isSafeProxyPath(path) {
100
+ if (!path.startsWith("/") || path.startsWith("//") || path.includes("\\")) return false;
101
+ if (/%2f|%5c/i.test(path)) return false;
102
+ const segments = path.slice(1).split("/");
103
+ return segments.every((segment, index) => (segment !== "" || index === segments.length - 1) && segment !== "." && segment !== "..");
104
+ }
105
+ function matchesPrefix(segments, prefix) {
106
+ return prefix.length > 0 && segments.length >= prefix.length && prefix.every((segment, index) => segments[index] === segment);
107
+ }
108
+ /**
109
+ * Validates a site-relative path against the supported endpoints. Returns the
110
+ * endpoint it belongs to, or `null` when the path is unsafe or outside the
111
+ * boundary.
112
+ */
113
+ function resolveJsonApiProxyPath(path, endpoints = {}) {
114
+ if (!isSafeProxyPath(path)) return null;
115
+ const apiPrefix = splitSegments(endpoints.apiPrefix || "jsonapi");
116
+ const routerPrefix = splitSegments(endpoints.routerPrefix || "router/translate-path");
117
+ const segments = path.slice(1).split("/").filter(Boolean);
118
+ const candidates = [segments];
119
+ if (segments.length > 1 && isSafeOptionalPrefix(segments[0])) candidates.push(segments.slice(1));
120
+ for (const candidate of candidates) {
121
+ if (matchesPrefix(candidate, apiPrefix)) return {
122
+ endpoint: "jsonapi",
123
+ path
124
+ };
125
+ if (matchesPrefix(candidate, routerPrefix)) return {
126
+ endpoint: "router",
127
+ path
128
+ };
129
+ }
130
+ return null;
131
+ }
132
+ /** Normalizes a backend base URL: absolute, no trailing slash. */
133
+ function normalizeBaseUrl(baseUrl) {
134
+ const url = new URL(baseUrl);
135
+ url.search = "";
136
+ url.hash = "";
137
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
138
+ }
139
+ /**
140
+ * Splits an absolute upstream URL into the part relative to the backend base
141
+ * URL. Returns `null` when the URL is not on the backend.
142
+ */
143
+ function toBackendRelativePath(url, baseUrl) {
144
+ let target;
145
+ try {
146
+ target = new URL(url);
147
+ } catch {
148
+ return null;
149
+ }
150
+ const base = new URL(normalizeBaseUrl(baseUrl));
151
+ if (target.origin !== base.origin) return null;
152
+ const basePath = base.pathname.replace(/\/+$/, "");
153
+ if (basePath !== "" && target.pathname !== basePath && !target.pathname.startsWith(`${basePath}/`)) return null;
154
+ return {
155
+ path: target.pathname.slice(basePath.length) || "/",
156
+ search: target.search
157
+ };
158
+ }
159
+ /**
160
+ * Maps an absolute upstream JSON:API URL to the same-origin proxy. Returns
161
+ * `null` for URLs that are not on the backend. Throws for backend URLs
162
+ * outside the supported endpoints, so an absolute Drupal URL can never bypass
163
+ * the proxy.
164
+ */
165
+ function mapJsonApiRequestToProxy(url, options) {
166
+ const api = resolveJsonApiBase(options.baseUrl, options);
167
+ const site = normalizeBaseUrl(options.baseUrl);
168
+ const endpoints = {
169
+ apiPrefix: api.apiPrefix,
170
+ routerPrefix: options.routerPrefix
171
+ };
172
+ const targets = api.foreign ? [{
173
+ base: api.base,
174
+ endpoint: "jsonapi"
175
+ }, {
176
+ base: site,
177
+ endpoint: "router"
178
+ }] : [{
179
+ base: site,
180
+ endpoint: null
181
+ }];
182
+ let origin;
183
+ try {
184
+ origin = new URL(url).origin;
185
+ } catch {
186
+ return null;
187
+ }
188
+ let onBackend = false;
189
+ for (const target of targets) {
190
+ if (new URL(target.base).origin === origin) onBackend = true;
191
+ const relative = toBackendRelativePath(url, target.base);
192
+ if (relative === null) continue;
193
+ const resolved = resolveJsonApiProxyPath(relative.path, endpoints);
194
+ if (resolved !== null && (target.endpoint === null || resolved.endpoint === target.endpoint) && (resolved.endpoint !== "jsonapi" || api.siteKnown || matchesPrefix(splitSegments(resolved.path), splitSegments(api.apiPrefix)))) return `${options.proxyUrl.replace(/\/+$/, "")}${resolved.path}${relative.search}`;
195
+ }
196
+ if (!onBackend) return null;
197
+ throw new Error(`[drupal-canvas] The browser JSON:API client only reaches the Drupal backend through the application proxy, and "${url}" is not a supported JSON:API or path-translation endpoint.`);
198
+ }
199
+ /**
200
+ * Maps a proxied request path back to its absolute upstream URL. Returns
201
+ * `null` when the path is unsafe or outside the supported endpoints.
202
+ */
203
+ function mapProxyPathToUpstream(proxiedPath, options) {
204
+ const proxyPath = new URL(options.proxyUrl, "http://localhost").pathname.replace(/\/+$/, "");
205
+ if (proxyPath !== "" && !proxiedPath.startsWith(`${proxyPath}/`)) return null;
206
+ const path = proxyPath === "" ? proxiedPath : proxiedPath.slice(proxyPath.length);
207
+ const api = resolveJsonApiBase(options.baseUrl, options);
208
+ const resolved = resolveJsonApiProxyPath(path, {
209
+ apiPrefix: api.apiPrefix,
210
+ routerPrefix: options.routerPrefix
211
+ });
212
+ if (resolved === null || resolved.endpoint === "jsonapi" && !api.siteKnown && !matchesPrefix(splitSegments(resolved.path), splitSegments(api.apiPrefix))) return null;
213
+ return {
214
+ url: `${resolved.endpoint === "jsonapi" ? api.base : normalizeBaseUrl(options.baseUrl)}${resolved.path}`,
215
+ endpoint: resolved.endpoint
216
+ };
217
+ }
218
+ // src/jsonapi-client.ts
219
+ /**
220
+ * @file
221
+ * The shared, framework-agnostic JSON:API client for Drupal Canvas. It
222
+ * extends `@drupal-api-client/json-api-client` with:
223
+ * - draft reads at a configured resource version (working copies), resolved
224
+ * before the configured serializer runs;
225
+ * - transparent mapping of browser requests to a same-origin proxy, including
226
+ * absolute pagination links and the path-translation endpoint;
227
+ * - draft-session errors surfaced as `DraftSessionError`;
228
+ * - client caches separated by resource version and session scope.
229
+ *
230
+ * The legacy `new JsonApiClient()` API remains for Drupal-rendered Code
231
+ * Components and Workbench; it reads `drupalSettings` and throws an actionable
232
+ * migration error elsewhere. Rendering integrations and the Headless SDK use
233
+ * `createJsonApiClient()` instead, which has no environment guard.
234
+ *
235
+ * @see docs/adr/0021-code-component-runtime-compatibility-across-frontend-modes.md
236
+ */
237
+ /**
238
+ * Thrown when the draft preview session is rejected: the application proxy
239
+ * reports it expired or invalid, or Drupal answers an authenticated request
240
+ * with 401. Never swallowed by the client's fallbacks.
241
+ */
242
+ var DraftSessionError = class extends Error {
243
+ status;
244
+ constructor(message, status = 401) {
245
+ super(message);
246
+ this.name = "DraftSessionError";
247
+ this.status = status;
248
+ }
249
+ };
250
+ function isDraftSessionError(error) {
251
+ return error instanceof DraftSessionError || typeof error === "object" && error !== null && error.name === "DraftSessionError";
252
+ }
253
+ function toUrlString(input) {
254
+ if (typeof input === "string") return input;
255
+ if (input instanceof URL) return input.href;
256
+ return input.url;
257
+ }
258
+ /**
259
+ * Creates the transport for the shared client: routes backend requests through
260
+ * the configured proxy, applies the credentials mode, and turns the proxy's
261
+ * draft-session errors into exceptions.
262
+ */
263
+ function createTransport(config) {
264
+ const fetchImpl = config.fetch ?? fetch;
265
+ return async (input, init) => {
266
+ let url = toUrlString(input);
267
+ if (config.proxyUrl) url = mapJsonApiRequestToProxy(url, {
268
+ baseUrl: config.baseUrl,
269
+ proxyUrl: config.proxyUrl,
270
+ apiPrefix: config.apiPrefix,
271
+ apiUrl: config.apiUrl,
272
+ apiSiteUrl: config.apiSiteUrl,
273
+ routerPrefix: config.routerPrefix
274
+ }) ?? url;
275
+ const request = { ...init };
276
+ if (config.credentials && request.credentials === void 0) request.credentials = config.credentials;
277
+ const response = await fetchImpl(url, request);
278
+ const optedOut = request.credentials === "omit";
279
+ const carriesSession = new Headers(request.headers).has("authorization") || !optedOut && (config.credentials === "same-origin" || config.credentials === "include" || config.fetchAuthenticates === true);
280
+ if (!config.proxyUrl && response.status === 401 && carriesSession) throw new DraftSessionError("The draft preview session was rejected by Drupal.", 401);
281
+ if (config.proxyUrl && response.headers.get("X-Canvas-Draft-Session") === "expired") {
282
+ let message = "The draft preview session has expired.";
283
+ try {
284
+ const body = await response.clone().json();
285
+ if (typeof body?.message === "string") message = body.message;
286
+ } catch {}
287
+ throw new DraftSessionError(message, response.status);
288
+ }
289
+ return response;
290
+ };
291
+ }
292
+ /** Prefixes every key of a cache so scopes never share entries. */
293
+ function scopeCache(cache, scope) {
294
+ return {
295
+ get: (key, ...args) => cache.get(`${scope}:${key}`, ...args),
296
+ set: (key, value, ...args) => cache.set(`${scope}:${key}`, value, ...args)
297
+ };
298
+ }
299
+ /**
300
+ * The shared client implementation. Construct it with
301
+ * {@link createJsonApiClient}; the legacy `JsonApiClient` constructor extends
302
+ * it for Drupal and Workbench.
303
+ */
304
+ var CanvasJsonApiClient = class extends JsonApiClient {
305
+ /** The serializable part of the configuration. */
306
+ runtimeConfig;
307
+ /** The resource version applied to reads, or `null`. */
308
+ resourceVersion;
309
+ /** Where JSON:API requests go (base URL, prefix, foreign site or not). */
310
+ apiBase;
311
+ /** Resource types Drupal reads without revisions (see `getResource()`). */
312
+ unversionedTypes = /* @__PURE__ */ new Set();
313
+ constructor(config) {
314
+ const baseUrl = normalizeBaseUrl(config.baseUrl);
315
+ const apiUrl = config.apiUrl ? normalizeBaseUrl(config.apiUrl) : void 0;
316
+ const api = resolveJsonApiBase(baseUrl, {
317
+ apiPrefix: config.apiPrefix,
318
+ apiUrl,
319
+ apiSiteUrl: config.apiSiteUrl
320
+ });
321
+ const apiPrefix = api.apiPrefix;
322
+ const routerPrefix = trimSlashes(config.routerPrefix ?? "router/translate-path") || "router/translate-path";
323
+ const resourceVersion = config.resourceVersion || null;
324
+ const sessionSensitive = Boolean(config.authentication) || Boolean(config.proxyUrl) || Boolean(config.fetch) || config.credentials === "same-origin" || config.credentials === "include" || config.credentials === void 0 && typeof window !== "undefined" || Boolean(config.preview) || resourceVersion !== null;
325
+ const cache = config.cache && (!sessionSensitive || config.cacheScope) ? scopeCache(config.cache, [resourceVersion ?? "default", config.cacheScope ?? "public"].join(":")) : void 0;
326
+ const serializer = config.serializer === void 0 ? new DefaultSerializer() : config.serializer ?? void 0;
327
+ super(baseUrl, {
328
+ ...config.upstreamOptions,
329
+ apiPrefix,
330
+ decoupledRouterApiPrefix: routerPrefix,
331
+ serializer,
332
+ cache,
333
+ authentication: config.authentication,
334
+ customFetch: createTransport({
335
+ ...config,
336
+ baseUrl
337
+ })
338
+ });
339
+ this.runtimeConfig = {
340
+ baseUrl,
341
+ apiPrefix,
342
+ ...apiUrl && { apiUrl },
343
+ ...apiUrl && config.apiSiteUrl && { apiSiteUrl: normalizeBaseUrl(config.apiSiteUrl) },
344
+ routerPrefix,
345
+ ...config.proxyUrl && { proxyUrl: config.proxyUrl },
346
+ resourceVersion,
347
+ preview: config.preview ?? false
348
+ };
349
+ this.resourceVersion = resourceVersion;
350
+ this.apiBase = api;
351
+ const router = this.router;
352
+ router.createURL = ({ localeSegment, path }) => `${baseUrl}/${localeSegment ? `${localeSegment}/` : ""}${routerPrefix}?path=${path}`;
353
+ }
354
+ /**
355
+ * Obtaining or renewing the configured credentials is part of the session
356
+ * lifecycle: a failure there (for example an OAuth renewal answered with
357
+ * `invalid_grant`) is a rejected session, never an ordinary request error
358
+ * that a collection read could paper over with published items.
359
+ */
360
+ async addAuthorizationHeader(options) {
361
+ try {
362
+ return await super.addAuthorizationHeader(options);
363
+ } catch (error) {
364
+ if (isDraftSessionError(error)) throw error;
365
+ throw new DraftSessionError(`The session credentials could not be obtained: ${error instanceof Error ? error.message : String(error)}`, 401);
366
+ }
367
+ }
368
+ /**
369
+ * Builds JSON:API URLs as Drupal serves them: the backend base URL
370
+ * including any site path, then a locale prefix, then the JSON:API prefix
371
+ * (the upstream builder resolves root-relative and would drop a site path
372
+ * such as `/sub`). A same-site full URL override is a prefix override; a
373
+ * foreign one has no known site root, so a locale prefix is refused.
374
+ */
375
+ async createURL(segments) {
376
+ const { localeSegment, entityTypeId, bundleId, viewName, viewDisplayId, resourceId, queryString } = segments;
377
+ if (localeSegment && !this.apiBase.siteKnown) throw new Error(`[drupal-canvas] A locale path prefix ("${localeSegment}") cannot be applied to a JSON:API base URL on another site (${this.apiBase.base}) without its site base URL (apiSiteUrl).`);
378
+ const prefixUrl = `${this.apiBase.base}/${localeSegment ? `${localeSegment}/` : ""}${this.apiPrefix}`;
379
+ const query = queryString ? `?${queryString}` : "";
380
+ if (this.indexLookup) {
381
+ const cacheKey = `${localeSegment ? `${localeSegment}/` : ""}${this.apiPrefix}`;
382
+ let index = await this.getCachedResponse(cacheKey);
383
+ if (!index) {
384
+ const { response, error } = await this.fetch(prefixUrl);
385
+ if (error) throw error;
386
+ index = await response.json();
387
+ if (this.cache && response.status < 400) await this.cache.set(cacheKey, index);
388
+ }
389
+ const href = index?.links?.[`${entityTypeId}${bundleId ? `--${bundleId}` : ""}`]?.href;
390
+ if (href) return `${href}${resourceId ? `/${resourceId}` : ""}${query}`;
391
+ }
392
+ return viewName ? `${prefixUrl}/views/${viewName}/${viewDisplayId}${query}` : `${prefixUrl}/${entityTypeId}${bundleId ? `/${bundleId}` : ""}${resourceId ? `/${resourceId}` : ""}${query}`;
393
+ }
394
+ /**
395
+ * Adds the configured resource version to a read unless the caller selected
396
+ * one explicitly.
397
+ */
398
+ withResourceVersion(options) {
399
+ if (this.resourceVersion === null || options?.queryString?.includes("resourceVersion=")) return options;
400
+ const version = `resourceVersion=${encodeURIComponent(this.resourceVersion)}`;
401
+ return {
402
+ ...options,
403
+ queryString: options?.queryString ? `${options.queryString}&${version}` : version
404
+ };
405
+ }
406
+ /**
407
+ * Resource reads apply the configured resource version. Drupal answers a
408
+ * versioned read of a resource type without revisions with 501 Not
409
+ * Implemented; the read is then repeated once without the version. When
410
+ * that returns the requested JSON:API resource without a `working-copy`
411
+ * link (which Drupal adds to every revisionable resource), the type is read
412
+ * without the version from then on. Any other response keeps the original
413
+ * one; a failed request throws as any read does. Raw responses and
414
+ * caller-selected versions bypass this.
415
+ */
416
+ async getResource(type, resourceId, options) {
417
+ const versioned = options?.rawResponse || this.unversionedTypes.has(type) ? options : this.withResourceVersion(options);
418
+ if (versioned === options) return super.getResource(type, resourceId, options);
419
+ const { entityTypeId, bundleId } = JsonApiClient.getEntityTypeIdAndBundleId(type);
420
+ const localeSegment = options?.locale || this.defaultLocale;
421
+ if (!options?.disableCache) {
422
+ const cached = await this.getCachedResponse(await JsonApiClient.createCacheKey({
423
+ entityTypeId,
424
+ bundleId,
425
+ resourceId,
426
+ localeSegment,
427
+ queryString: versioned?.queryString
428
+ }));
429
+ if (cached) return cached;
430
+ }
431
+ const { response, json } = await super.getResource(type, resourceId, {
432
+ ...versioned,
433
+ rawResponse: true
434
+ });
435
+ if (!await isNotImplementedResponse(response)) return json;
436
+ const url = await this.createURL({
437
+ localeSegment,
438
+ entityTypeId,
439
+ bundleId,
440
+ resourceId,
441
+ queryString: options?.queryString
442
+ });
443
+ const retry = await this.fetch(url, options?.disableAuthentication ? { credentials: "omit" } : {});
444
+ if (retry.error) throw retry.error;
445
+ if (!isUnversionedResourceDocument(retry.response.ok && isJsonApiResponse(retry.response) ? await retry.response.clone().json().catch(() => null) : null, type, resourceId)) return json;
446
+ this.unversionedTypes.add(type);
447
+ return await this.processApiResponseAndParseBody(retry.response, await JsonApiClient.createCacheKey({
448
+ entityTypeId,
449
+ bundleId,
450
+ resourceId,
451
+ localeSegment,
452
+ queryString: options?.queryString
453
+ }), options);
454
+ }
455
+ async getCollection(type, options) {
456
+ if (this.resourceVersion === null || options?.rawResponse) return super.getCollection(type, options);
457
+ const { entityTypeId, bundleId } = JsonApiClient.getEntityTypeIdAndBundleId(type);
458
+ const localeSegment = options?.locale || this.defaultLocale;
459
+ const cacheKey = await JsonApiClient.createCacheKey({
460
+ entityTypeId,
461
+ bundleId,
462
+ localeSegment,
463
+ queryString: options?.queryString,
464
+ cacheKey: options?.cacheKey
465
+ });
466
+ if (!options?.disableCache) {
467
+ const cached = await this.getCachedResponse(cacheKey);
468
+ if (cached) return cached;
469
+ }
470
+ const url = await this.createURL({
471
+ localeSegment,
472
+ entityTypeId,
473
+ bundleId,
474
+ queryString: options?.queryString
475
+ });
476
+ const init = options?.disableAuthentication ? { credentials: "omit" } : {};
477
+ const { response, error } = await this.fetch(url, init);
478
+ if (error) throw error;
479
+ const status = response.status;
480
+ let document = status === 204 ? "" : await response.json();
481
+ if (status < 400 && isCollectionDocument(document)) document = await this.hydrateWorkingCopies(type, document, init, {
482
+ localeSegment,
483
+ queryString: options?.queryString
484
+ });
485
+ const result = this.serializer?.deserialize ? this.serializer.deserialize(document) : document;
486
+ if (this.cache && !options?.disableCache && status < 400) await this.cache.set(cacheKey, result);
487
+ return result;
488
+ }
489
+ /**
490
+ * Replaces each collection item with its working copy. Item reads keep the
491
+ * read options that apply to a single resource — the locale, sparse
492
+ * fieldsets, includes, and a resource version the caller selected
493
+ * explicitly — but not collection-only parameters (filter, sort, page).
494
+ * Included resources returned with the working copies replace the
495
+ * collection's included resources of the same identity, so relationships
496
+ * of a working copy resolve against the document.
497
+ */
498
+ async hydrateWorkingCopies(type, document, init, read) {
499
+ const { entityTypeId, bundleId } = JsonApiClient.getEntityTypeIdAndBundleId(type);
500
+ const itemParams = new URLSearchParams();
501
+ for (const [key, value] of new URLSearchParams(read.queryString ?? "")) if (key === "include" || key === "resourceVersion" || /^fields\[[^\]]+\]$/.test(key)) itemParams.append(key, value);
502
+ if (!itemParams.has("resourceVersion")) itemParams.set("resourceVersion", this.resourceVersion);
503
+ const included = /* @__PURE__ */ new Map();
504
+ const includedKey = (resource) => typeof resource === "object" && resource !== null && typeof resource.type === "string" && typeof resource.id === "string" ? `${resource.type}:${resource.id}` : null;
505
+ if (Array.isArray(document.included)) for (const resource of document.included) {
506
+ const key = includedKey(resource);
507
+ if (key !== null) included.set(key, resource);
508
+ }
509
+ const data = await Promise.all(document.data.map(async (item) => {
510
+ if (typeof item?.id !== "string" || !hasWorkingCopyLink(item)) return item;
511
+ const url = await this.createURL({
512
+ localeSegment: read.localeSegment,
513
+ entityTypeId,
514
+ bundleId,
515
+ resourceId: item.id,
516
+ queryString: itemParams.toString()
517
+ });
518
+ try {
519
+ const { response, error } = await this.fetch(url, init);
520
+ if (error) throw error;
521
+ if (!response.ok) return item;
522
+ const workingCopy = await response.json();
523
+ if (!workingCopy || typeof workingCopy !== "object" || !("data" in workingCopy) || !workingCopy.data) return item;
524
+ if (Array.isArray(workingCopy.included)) for (const resource of workingCopy.included) {
525
+ const key = includedKey(resource);
526
+ if (key !== null) included.set(key, resource);
527
+ }
528
+ return workingCopy.data;
529
+ } catch (error) {
530
+ if (isDraftSessionError(error)) throw error;
531
+ return item;
532
+ }
533
+ }));
534
+ for (const item of data) {
535
+ const key = includedKey(item);
536
+ if (key !== null) included.delete(key);
537
+ }
538
+ return {
539
+ ...document,
540
+ data,
541
+ ...included.size > 0 ? { included: [...included.values()] } : Array.isArray(document.included) ? { included: [] } : {}
542
+ };
543
+ }
544
+ };
545
+ /**
546
+ * Whether a resource object links to its working copy, which Drupal does for
547
+ * every resource of a revisionable type, including under sparse fieldsets.
548
+ */
549
+ function hasWorkingCopyLink(resource) {
550
+ const links = resource.links;
551
+ return typeof links === "object" && links !== null && "working-copy" in links;
552
+ }
553
+ /** Whether a response declares the JSON:API media type. */
554
+ function isJsonApiResponse(response) {
555
+ return (response.headers.get("content-type")?.split(";")[0])?.trim().toLowerCase() === "application/vnd.api+json";
556
+ }
557
+ /**
558
+ * Whether a response is Drupal's JSON:API 501 Not Implemented error, which
559
+ * answers a versioned read of a resource type without revisions.
560
+ */
561
+ async function isNotImplementedResponse(response) {
562
+ if (response.status !== 501 || !isJsonApiResponse(response)) return false;
563
+ try {
564
+ const document = await response.json();
565
+ return Array.isArray(document?.errors) && document.errors.some((error) => error?.status === "501");
566
+ } catch {
567
+ return false;
568
+ }
569
+ }
570
+ /**
571
+ * Whether a document holds the requested resource as a resource object of a
572
+ * type without revisions: it has links, but none to a working copy.
573
+ */
574
+ function isUnversionedResourceDocument(document, type, resourceId) {
575
+ const data = document?.data;
576
+ return typeof data === "object" && data !== null && !Array.isArray(data) && data.type === type && data.id === resourceId && typeof data.links === "object" && data.links !== null && !Array.isArray(data.links) && !hasWorkingCopyLink(data);
577
+ }
578
+ function isCollectionDocument(value) {
579
+ return typeof value === "object" && value !== null && Array.isArray(value.data);
580
+ }
581
+ /**
582
+ * Creates the shared JSON:API client from explicit configuration. This is the
583
+ * construction path for rendering integrations and the Headless SDK; it has
584
+ * no environment guard.
585
+ */
586
+ function createJsonApiClient(config) {
587
+ return new CanvasJsonApiClient(config);
588
+ }
589
+ /**
590
+ * The legacy JSON:API client for Drupal-rendered Code Components and
591
+ * Workbench: configured from `drupalSettings`, with `DefaultSerializer` and
592
+ * the site's JSON:API prefix. Outside those environments it throws an
593
+ * actionable migration error, even when a base URL is supplied.
594
+ *
595
+ * @deprecated Use `useJsonApiClient()` in React Code Components, or the
596
+ * Headless SDK's `getClient()` in headless server code.
597
+ */
598
+ var LegacyJsonApiClient = class extends CanvasJsonApiClient {
599
+ constructor(baseUrl, options) {
600
+ assertLegacyRuntime("new JsonApiClient()");
601
+ const settings = globalThis.drupalSettings?.canvasData?.v0;
602
+ if (settings?.jsonapiSettings === null) throw new Error("The JSON:API module is not installed. Please install it to use JsonApiClient.");
603
+ const clientBaseUrl = baseUrl || settings?.baseUrl;
604
+ if (!clientBaseUrl) throw new Error("Could not determine your site's base URL for the JSON:API client. If working outside of Drupal Canvas, you can use the @drupal-canvas/vite-plugin to automatically configure it for you. Otherwise you must explicitly provide a base URL, i.e. `const client = new JsonApiClient(\"https://...\")`");
605
+ const { apiPrefix, authentication, cache, customFetch, decoupledRouterApiPrefix, serializer, ...upstreamOptions } = options ?? {};
606
+ super({
607
+ baseUrl: clientBaseUrl,
608
+ apiPrefix: apiPrefix ?? settings?.jsonapiSettings?.apiPrefix,
609
+ routerPrefix: decoupledRouterApiPrefix,
610
+ authentication,
611
+ cache,
612
+ cacheScope: options?.cacheScope,
613
+ fetch: customFetch,
614
+ serializer: options && "serializer" in options ? serializer ?? null : void 0,
615
+ upstreamOptions
616
+ });
617
+ }
618
+ };
3
619
  export { CanvasJsonApiClient, DEFAULT_JSONAPI_PREFIX, DEFAULT_ROUTER_PREFIX, DraftSessionError, JSONAPI_DRAFT_SESSION_EXPIRED_ERROR, JSONAPI_PROXY_SESSION_EXPIRED, JSONAPI_PROXY_SESSION_HEADER, LegacyJsonApiClient as JsonApiClient, createJsonApiClient, isDraftSessionError, isSafeProxyPath, mapJsonApiRequestToProxy, mapProxyPathToUpstream, normalizeBaseUrl, resolveJsonApiBase, resolveJsonApiProxyPath, toBackendRelativePath, trimSlashes };
@@ -1,4 +1,3 @@
1
- //#region src/jsonapi-utils.d.ts
2
1
  interface Node {
3
2
  path?: {
4
3
  alias?: string;
@@ -19,7 +18,7 @@ interface MenuItem {
19
18
  *
20
19
  * @return string
21
20
  */
22
- declare function getNodePath(node: Node): string;
21
+ export declare function getNodePath(node: Node): string;
23
22
  /**
24
23
  * Sort menu items from jsonapi_menu_items module into a tree with additional
25
24
  * _children and _hasSubmenu properties.
@@ -28,6 +27,4 @@ declare function getNodePath(node: Node): string;
28
27
  *
29
28
  * @return menuItems
30
29
  */
31
- declare function sortMenu(menuItems: MenuItem[]): MenuItem[];
32
- //#endregion
33
- export { getNodePath, sortMenu };
30
+ export declare function sortMenu(menuItems: MenuItem[]): MenuItem[];
@@ -1,4 +1,4 @@
1
- //#region src/jsonapi-utils.ts
1
+ // src/jsonapi-utils.ts
2
2
  /**
3
3
  * Given a node returned from JSON:API, return either the path alias or fall back
4
4
  * to /node/x path.
@@ -38,5 +38,4 @@ function sortMenu(menuItems) {
38
38
  });
39
39
  return menu;
40
40
  }
41
- //#endregion
42
41
  export { getNodePath, sortMenu };
@@ -1,4 +1,4 @@
1
- //#region src/runtime.ts
1
+ // src/runtime.ts
2
2
  /**
3
3
  * The global property holding the marker. Integrations that cannot import this
4
4
  * package (Drupal's classic hydration script) set it directly.
@@ -26,8 +26,7 @@ function getCanvasRuntime() {
26
26
  function isLegacyRuntimeSupported() {
27
27
  return getCanvasRuntime() !== null;
28
28
  }
29
- //#endregion
30
- //#region src/migration.ts
29
+ // src/migration.ts
31
30
  /**
32
31
  * @file
33
32
  * Migration guidance shared by the legacy API errors, the hook warnings, and
@@ -59,5 +58,4 @@ function formatLegacyApiError(api) {
59
58
  function assertLegacyRuntime(api) {
60
59
  if (!isLegacyRuntimeSupported()) throw new Error(formatLegacyApiError(api));
61
60
  }
62
- //#endregion
63
61
  export { declareCanvasRuntime as a, formatLegacyApiError as i, LEGACY_API_GUIDANCE as n, getCanvasRuntime as o, assertLegacyRuntime as r, isLegacyRuntimeSupported as s, AGENT_MIGRATION_PROMPT as t };
@@ -1,7 +1,4 @@
1
1
  import { ImageLoaderParams, ImageProps } from "next-image-standalone";
2
- //#region src/next-image-standalone.d.ts
3
- declare function Image(props: Omit<ImageProps, 'loader'> & {
2
+ export default function Image(props: Omit<ImageProps, 'loader'> & {
4
3
  loader?: (params: ImageLoaderParams) => string;
5
- }): import("react/jsx-runtime").JSX.Element;
6
- //#endregion
7
- export { Image as default };
4
+ }): import("react/jsx-runtime").JSX.Element;