@cmssy/react 4.7.2 → 5.0.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/index.js CHANGED
@@ -1,38 +1,10 @@
1
+ import { buildBlockContext, getBlockContentForLanguage, asBucket, resolveSiteLocales } from '@cmssy/core';
2
+ export { CmssyRequestError, DEFAULT_CMSSY_API_URL, FORM_QUERY, MODEL_DEFINITIONS_QUERY, MODEL_RECORDS_QUERY, PROTOCOL_VERSION, SITE_CONFIG_QUERY, SUBMIT_FORM_MUTATION, buildBlockContext, buildLocaleSwitchHref, collectFormIds, createCmssyClient, fetchLayouts, fetchPage, fetchPageById, fetchPageMeta, fetchPages, fetchSiteConfig, fields, getBlockContentForLanguage, graphqlRequest, isProtocolCompatible, localizeHref, localizeHtmlLinks, normalizeOrigin, normalizeSlug, parseEditorMessage, postToEditor, resolveApiUrl, resolveForms, resolvePublicUrl, resolveSiteLocales, resolveWorkspaceId, splitLocaleFromPath } from '@cmssy/core';
1
3
  import { createElement } from 'react';
2
4
  import { jsx, Fragment } from 'react/jsx-runtime';
3
5
  export { evaluateFieldConditionGroup } from '@cmssy/types';
4
6
 
5
- // src/fields.ts
6
- function control(type) {
7
- return (opts = {}) => ({
8
- type,
9
- label: opts.label ?? "",
10
- ...opts
11
- });
12
- }
13
- var fields = {
14
- text: control("text"),
15
- textarea: control("textarea"),
16
- richText: control("richText"),
17
- markdown: control("markdown"),
18
- number: control("number"),
19
- date: control("date"),
20
- datetime: control("datetime"),
21
- boolean: control("boolean"),
22
- color: control("color"),
23
- media: control("media"),
24
- link: control("link"),
25
- url: control("url"),
26
- email: control("email"),
27
- select: control("select"),
28
- multiselect: control("multiselect"),
29
- radio: control("radio"),
30
- repeater: control("repeater"),
31
- table: control("table"),
32
- json: control("json"),
33
- form: control("form"),
34
- pageSelector: control("pageSelector")
35
- };
7
+ // src/index.ts
36
8
 
37
9
  // src/registry.ts
38
10
  function defineBlock(def) {
@@ -75,48 +47,6 @@ function blocksToMeta(blocks, defaults = {}) {
75
47
  }
76
48
  return out;
77
49
  }
78
-
79
- // src/components/block-context.ts
80
- function buildBlockContext(locale, defaultLocale, enabledLocales, isPreview, forms, extra) {
81
- return {
82
- locale: {
83
- current: locale,
84
- default: defaultLocale,
85
- enabled: enabledLocales && enabledLocales.length > 0 ? enabledLocales : Array.from(/* @__PURE__ */ new Set([defaultLocale, locale]))
86
- },
87
- isPreview: isPreview ?? false,
88
- forms,
89
- ...extra?.auth ? { auth: extra.auth } : {},
90
- ...extra?.workspace ? { workspace: extra.workspace } : {}
91
- };
92
- }
93
-
94
- // src/content/get-block-content.ts
95
- function isPlainObject(value) {
96
- return typeof value === "object" && value !== null && !Array.isArray(value);
97
- }
98
- function looksLikeLocaleKey(key) {
99
- return /^[a-z]{2}(-[A-Za-z]{2})?$/.test(key);
100
- }
101
- function getBlockContentForLanguage(content, locale, defaultLocale = "en", availableLocales) {
102
- if (!isPlainObject(content)) return {};
103
- const isLocale = availableLocales ? (key) => availableLocales.includes(key) : looksLikeLocaleKey;
104
- const localeEntries = Object.entries(content).filter(
105
- ([key, value]) => isLocale(key) && isPlainObject(value)
106
- );
107
- if (localeEntries.length === 0) return { ...content };
108
- const localeMap = Object.fromEntries(localeEntries);
109
- const nonTranslatable = {};
110
- for (const [key, value] of Object.entries(content)) {
111
- if (!(isLocale(key) && isPlainObject(value))) nonTranslatable[key] = value;
112
- }
113
- const fallbackKey = Object.keys(localeMap)[0];
114
- const chosen = localeMap[locale] ?? localeMap[defaultLocale] ?? localeMap[fallbackKey];
115
- return { ...nonTranslatable, ...chosen };
116
- }
117
- function asBucket(value) {
118
- return isPlainObject(value) ? value : {};
119
- }
120
50
  var WARN_CAP = 256;
121
51
  var warned = /* @__PURE__ */ new Set();
122
52
  function UnknownBlock({ type }) {
@@ -153,8 +83,6 @@ function renderResolvedBlock(block, map, locale, defaultLocale, options = {}) {
153
83
  block.id
154
84
  );
155
85
  }
156
-
157
- // src/components/resolve-blocks.ts
158
86
  async function resolveBlocks(blocks, loaderMap, locale, defaultLocale, context, enabledLocales) {
159
87
  return Promise.all(
160
88
  blocks.map(async (block) => {
@@ -182,423 +110,6 @@ async function resolveBlocks(blocks, loaderMap, locale, defaultLocale, context,
182
110
  })
183
111
  );
184
112
  }
185
-
186
- // src/data/http.ts
187
- var CmssyRequestError = class extends Error {
188
- status;
189
- constructor(message, status) {
190
- super(message);
191
- this.name = "CmssyRequestError";
192
- this.status = status;
193
- }
194
- };
195
- var DEFAULT_RETRY_STATUSES = [429, 503];
196
- function retryAfterMs(response) {
197
- const raw = response.headers?.get("retry-after");
198
- if (!raw) return null;
199
- const seconds = Number(raw);
200
- if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
201
- const date = Date.parse(raw);
202
- if (Number.isFinite(date)) return Math.max(0, date - Date.now());
203
- return null;
204
- }
205
- function sleep(ms, signal) {
206
- return new Promise((resolve, reject) => {
207
- if (signal?.aborted) {
208
- reject(new Error("cmssy: request aborted"));
209
- return;
210
- }
211
- const timer = setTimeout(() => {
212
- signal?.removeEventListener("abort", onAbort);
213
- resolve();
214
- }, ms);
215
- function onAbort() {
216
- clearTimeout(timer);
217
- reject(new Error("cmssy: request aborted"));
218
- }
219
- signal?.addEventListener("abort", onAbort, { once: true });
220
- });
221
- }
222
- async function fetchWithRetry(doFetch, url, init, retry) {
223
- if (retry === false || retry === void 0) {
224
- return doFetch(url, init);
225
- }
226
- const maxRetries = retry.maxRetries ?? 3;
227
- const baseDelayMs = retry.baseDelayMs ?? 300;
228
- const maxDelayMs = retry.maxDelayMs ?? 3e3;
229
- const retryStatuses = retry.retryStatuses ?? DEFAULT_RETRY_STATUSES;
230
- let response = await doFetch(url, init);
231
- for (let attempt = 0; attempt < maxRetries; attempt++) {
232
- if (response.ok || !retryStatuses.includes(response.status)) {
233
- return response;
234
- }
235
- const backoff = baseDelayMs * 2 ** attempt;
236
- const wait = Math.min(retryAfterMs(response) ?? backoff, maxDelayMs);
237
- await sleep(wait, init.signal);
238
- response = await doFetch(url, init);
239
- }
240
- return response;
241
- }
242
- async function postGraphql(url, query, variables, options) {
243
- const doFetch = options.fetch ?? globalThis.fetch;
244
- if (typeof doFetch !== "function") {
245
- throw new Error(
246
- "cmssy: no fetch implementation available - pass options.fetch"
247
- );
248
- }
249
- const response = await fetchWithRetry(
250
- doFetch,
251
- url,
252
- {
253
- method: "POST",
254
- headers: { "content-type": "application/json", ...options.headers },
255
- body: JSON.stringify({ query, variables }),
256
- signal: options.signal
257
- },
258
- options.retry
259
- );
260
- if (!response.ok) {
261
- let detail = "";
262
- try {
263
- const body = await response.json();
264
- if (body.errors && body.errors.length > 0) {
265
- detail = ` - ${body.errors.map((error) => error.message ?? "GraphQL error").join("; ")}`;
266
- }
267
- } catch {
268
- detail = "";
269
- }
270
- throw new CmssyRequestError(
271
- `cmssy: ${options.label} failed (${response.status})${detail}`,
272
- response.status
273
- );
274
- }
275
- let json;
276
- try {
277
- json = await response.json();
278
- } catch {
279
- throw new Error(`cmssy: invalid JSON response from the ${options.label}`);
280
- }
281
- if (json.errors && json.errors.length > 0) {
282
- const message = json.errors.map((error) => error.message ?? "GraphQL error").join("; ");
283
- throw new Error(`cmssy: ${options.label} error - ${message}`);
284
- }
285
- return json.data;
286
- }
287
-
288
- // src/content/content-client.ts
289
- var DEFAULT_CMSSY_API_URL = "https://api.cmssy.io/graphql";
290
- function resolveApiUrl(apiUrl) {
291
- const explicit = apiUrl?.trim();
292
- if (explicit) return explicit;
293
- const env = globalThis.process?.env;
294
- const fromEnv = env?.CMSSY_API_URL?.trim() ?? "";
295
- return fromEnv.length > 0 ? fromEnv : DEFAULT_CMSSY_API_URL;
296
- }
297
- function resolvePublicUrl(config) {
298
- const base = resolveApiUrl(config.apiUrl).replace(/\/graphql\/?$/, "");
299
- return `${base}/public/${config.org}/${config.workspaceSlug}/graphql`;
300
- }
301
- var PUBLIC_PAGE_QUERY = `query PublicPage($workspaceSlug: String!, $slug: String!, $previewSecret: String) {
302
- public {
303
- page {
304
- get(workspaceSlug: $workspaceSlug, slug: $slug, previewSecret: $previewSecret) {
305
- id
306
- blocks { id type content style advanced }
307
- publishedBlocks { id type content style advanced }
308
- }
309
- }
310
- }
311
- }`;
312
- var PUBLIC_PAGE_DEV_QUERY = `query PublicPage($workspaceSlug: String!, $slug: String!, $previewSecret: String, $devPreview: Boolean) {
313
- public {
314
- page {
315
- get(workspaceSlug: $workspaceSlug, slug: $slug, previewSecret: $previewSecret, devPreview: $devPreview) {
316
- id
317
- blocks { id type content style advanced }
318
- publishedBlocks { id type content style advanced }
319
- }
320
- }
321
- }
322
- }`;
323
- var PUBLIC_PAGE_BY_ID_QUERY = `query PublicPageById($workspaceSlug: String!, $pageId: ID!) {
324
- public {
325
- page {
326
- getById(workspaceSlug: $workspaceSlug, pageId: $pageId) {
327
- id
328
- publishedBlocks { id type content style advanced }
329
- }
330
- }
331
- }
332
- }`;
333
- var PUBLIC_PAGES_QUERY = `query PublicPages($workspaceSlug: String!) {
334
- public {
335
- page {
336
- list(workspaceSlug: $workspaceSlug) {
337
- id
338
- slug
339
- updatedAt
340
- publishedAt
341
- }
342
- }
343
- }
344
- }`;
345
- var PUBLIC_PAGE_META_QUERY = `query PublicPageMeta($workspaceSlug: String!, $slug: String!) {
346
- public {
347
- page {
348
- get(workspaceSlug: $workspaceSlug, slug: $slug) {
349
- id
350
- seoTitle
351
- seoDescription
352
- seoKeywords
353
- displayName
354
- }
355
- }
356
- }
357
- }`;
358
- var PUBLIC_PAGE_LAYOUTS_QUERY = `query PublicPageLayouts($workspaceSlug: String!, $pageSlug: String!, $previewSecret: String) {
359
- public {
360
- page {
361
- layouts(workspaceSlug: $workspaceSlug, pageSlug: $pageSlug, previewSecret: $previewSecret) {
362
- position
363
- blocks { id type content style advanced order isActive }
364
- settings { desktopWidth mobileBehavior }
365
- }
366
- }
367
- }
368
- }`;
369
- function normalizeSlug(path) {
370
- if (Array.isArray(path)) {
371
- const joined = path.filter(Boolean).join("/");
372
- return joined ? `/${joined}` : "/";
373
- }
374
- if (!path || path === "/") return "/";
375
- return path.startsWith("/") ? path : `/${path}`;
376
- }
377
- async function fetchPage(config, path, options = {}) {
378
- const slug = normalizeSlug(path);
379
- const trimmedSecret = options.previewSecret?.trim();
380
- const previewSecret = trimmedSecret ? trimmedSecret : null;
381
- const devToken = options.devToken?.trim();
382
- const devPreview = Boolean(options.devPreview && devToken);
383
- const headers = {};
384
- if (devPreview && devToken) {
385
- headers["authorization"] = `Bearer ${devToken}`;
386
- if (options.workspaceId) {
387
- headers["x-workspace-id"] = options.workspaceId;
388
- }
389
- }
390
- const data = await postGraphql(
391
- resolvePublicUrl(config),
392
- devPreview ? PUBLIC_PAGE_DEV_QUERY : PUBLIC_PAGE_QUERY,
393
- {
394
- workspaceSlug: config.workspaceSlug,
395
- slug,
396
- previewSecret,
397
- ...devPreview ? { devPreview: true } : {}
398
- },
399
- {
400
- fetch: options.fetch,
401
- signal: options.signal,
402
- headers,
403
- retry: options.retry ?? {},
404
- label: "page fetch"
405
- }
406
- );
407
- const page = data?.public?.page?.get;
408
- if (!page) return null;
409
- const draft = previewSecret !== null || devPreview;
410
- const blocks = (draft ? page.blocks : page.publishedBlocks) ?? [];
411
- return { id: page.id, blocks };
412
- }
413
- async function fetchPageById(config, pageId, options = {}) {
414
- const data = await postGraphql(
415
- resolvePublicUrl(config),
416
- PUBLIC_PAGE_BY_ID_QUERY,
417
- { workspaceSlug: config.workspaceSlug, pageId },
418
- {
419
- fetch: options.fetch,
420
- signal: options.signal,
421
- retry: options.retry ?? {},
422
- label: "page-by-id fetch"
423
- }
424
- );
425
- const page = data?.public?.page?.getById;
426
- if (!page) return null;
427
- return { id: page.id, blocks: page.publishedBlocks ?? [] };
428
- }
429
- async function fetchPages(config, options = {}) {
430
- const data = await postGraphql(
431
- resolvePublicUrl(config),
432
- PUBLIC_PAGES_QUERY,
433
- { workspaceSlug: config.workspaceSlug },
434
- {
435
- fetch: options.fetch,
436
- signal: options.signal,
437
- retry: options.retry ?? {},
438
- label: "pages fetch"
439
- }
440
- );
441
- return data?.public?.page?.list ?? [];
442
- }
443
- async function fetchPageMeta(config, path, options = {}) {
444
- const slug = normalizeSlug(path);
445
- const data = await postGraphql(
446
- resolvePublicUrl(config),
447
- PUBLIC_PAGE_META_QUERY,
448
- { workspaceSlug: config.workspaceSlug, slug },
449
- {
450
- fetch: options.fetch,
451
- signal: options.signal,
452
- retry: options.retry ?? {},
453
- label: "page meta fetch"
454
- }
455
- );
456
- return data?.public?.page?.get ?? null;
457
- }
458
- async function fetchLayouts(config, path, options = {}) {
459
- const pageSlug = normalizeSlug(path);
460
- const trimmedSecret = options.previewSecret?.trim();
461
- const previewSecret = trimmedSecret ? trimmedSecret : null;
462
- const data = await postGraphql(
463
- resolvePublicUrl(config),
464
- PUBLIC_PAGE_LAYOUTS_QUERY,
465
- { workspaceSlug: config.workspaceSlug, pageSlug, previewSecret },
466
- {
467
- fetch: options.fetch,
468
- signal: options.signal,
469
- retry: options.retry ?? {},
470
- label: "layouts fetch"
471
- }
472
- );
473
- return data?.public?.page?.layouts ?? [];
474
- }
475
-
476
- // src/data/graphql-request.ts
477
- async function graphqlRequest(config, query, variables, options = {}, label = "request") {
478
- const url = options.public ? resolvePublicUrl(config) : resolveApiUrl(config.apiUrl);
479
- return postGraphql(url, query, variables, {
480
- fetch: options.fetch,
481
- signal: options.signal,
482
- headers: options.headers,
483
- retry: options.retry,
484
- label
485
- });
486
- }
487
-
488
- // src/data/queries.ts
489
- var SITE_CONFIG_QUERY = `query PublicSiteConfig($workspaceSlug: String!) {
490
- public {
491
- siteConfig(workspaceSlug: $workspaceSlug) {
492
- id
493
- workspaceId
494
- siteName
495
- defaultLanguage
496
- enabledLanguages
497
- enabledFeatures
498
- notFoundPageId
499
- previewUrl
500
- branding {
501
- brandName
502
- logoUrl
503
- faviconUrl
504
- ogImageUrl
505
- }
506
- }
507
- }
508
- }`;
509
- var MODEL_DEFINITIONS_QUERY = `query PublicModelDefinitions($workspaceId: String!) {
510
- public {
511
- model {
512
- definitions(workspaceId: $workspaceId) {
513
- id name slug description icon color displayField recordCount
514
- }
515
- }
516
- }
517
- }`;
518
- var MODEL_RECORDS_QUERY = `query PublicModelRecords($workspaceId: String!, $modelSlug: String!, $filter: JSON, $sort: String, $locale: String, $limit: Int, $offset: Int, $populate: [String!]) {
519
- public {
520
- model {
521
- records(workspaceId: $workspaceId, modelSlug: $modelSlug, filter: $filter, sort: $sort, locale: $locale, limit: $limit, offset: $offset, populate: $populate) {
522
- items { id modelId data status createdAt updatedAt }
523
- total
524
- hasMore
525
- }
526
- }
527
- }
528
- }`;
529
- var FORM_QUERY = `query PublicForm($formId: ID!) {
530
- public {
531
- form {
532
- get(formId: $formId) {
533
- id
534
- name
535
- slug
536
- description
537
- fields {
538
- id name fieldType label placeholder helpText
539
- defaultValue width order showWhen requiredWhen
540
- options { value label disabled }
541
- validation { required minLength maxLength minValue maxValue pattern customMessage }
542
- }
543
- settings {
544
- actionType submitButtonLabel successMessage errorMessage
545
- redirectUrl requireLogin enableCaptcha
546
- }
547
- }
548
- }
549
- }
550
- }`;
551
- var SUBMIT_FORM_MUTATION = `mutation SubmitForm($formId: ID!, $input: SubmitFormInput!) {
552
- public {
553
- form {
554
- submit(formId: $formId, input: $input) {
555
- success message submissionId redirectUrl accessToken customer
556
- }
557
- }
558
- }
559
- }`;
560
-
561
- // src/data/site-locales.ts
562
- var TTL_MS = 6e4;
563
- var MAX_ENTRIES = 64;
564
- var cache = /* @__PURE__ */ new Map();
565
- async function resolveSiteLocales(config, options) {
566
- const key = `${resolveApiUrl(config.apiUrl)}::${config.org}::${config.workspaceSlug}`;
567
- const cached = cache.get(key);
568
- if (cached && cached.expires > Date.now()) return cached.value;
569
- cache.delete(key);
570
- let value;
571
- try {
572
- const data = await graphqlRequest(
573
- config,
574
- SITE_CONFIG_QUERY,
575
- { workspaceSlug: config.workspaceSlug },
576
- { ...options, public: true, retry: options?.retry ?? {} },
577
- "site config"
578
- );
579
- const siteConfig = data.public?.siteConfig ?? null;
580
- const defaultLocale = siteConfig?.defaultLanguage || "en";
581
- const enabled = siteConfig?.enabledLanguages ?? [];
582
- value = {
583
- defaultLocale,
584
- locales: enabled.length > 0 ? enabled : [defaultLocale]
585
- };
586
- } catch {
587
- value = { defaultLocale: "en", locales: ["en"] };
588
- }
589
- if (cache.size >= MAX_ENTRIES) cache.clear();
590
- cache.set(key, { value, expires: Date.now() + TTL_MS });
591
- return value;
592
- }
593
- function splitLocaleFromPath(path, siteLocales) {
594
- const first = path?.[0];
595
- if (first && first !== siteLocales.defaultLocale && siteLocales.locales.includes(first)) {
596
- return { locale: first, path: path.slice(1) };
597
- }
598
- return { locale: siteLocales.defaultLocale, path };
599
- }
600
-
601
- // src/components/resolve-render-locale.ts
602
113
  var warned2 = false;
603
114
  async function resolveRenderLocale({
604
115
  locale,
@@ -710,247 +221,6 @@ async function CmssyServerLayout({
710
221
  })
711
222
  ) });
712
223
  }
713
-
714
- // src/bridge/protocol.ts
715
- var PROTOCOL_VERSION = 2;
716
- function isProtocolCompatible(version) {
717
- return version === PROTOCOL_VERSION;
718
- }
719
-
720
- // src/bridge/messages.ts
721
- function normalizeOrigin(origin) {
722
- const trimmed = origin.trim();
723
- if (trimmed === "*") return "*";
724
- try {
725
- return new URL(trimmed).origin;
726
- } catch {
727
- return trimmed;
728
- }
729
- }
730
- function postToEditor(target, editorOrigin, message) {
731
- target.postMessage(message, normalizeOrigin(editorOrigin));
732
- }
733
- function isOriginAllowed(origin, allowed) {
734
- const list = Array.isArray(allowed) ? allowed : [allowed];
735
- const actual = normalizeOrigin(origin);
736
- return list.some((candidate) => {
737
- const expected = normalizeOrigin(candidate);
738
- return expected === "*" || expected === actual;
739
- });
740
- }
741
- function isObject(value) {
742
- return typeof value === "object" && value !== null && !Array.isArray(value);
743
- }
744
- function parseEditorMessage(data, origin, expectedOrigin) {
745
- if (!isOriginAllowed(origin, expectedOrigin)) return null;
746
- if (!isObject(data)) return null;
747
- switch (data.type) {
748
- case "cmssy:select":
749
- return typeof data.blockId === "string" && data.protocolVersion === PROTOCOL_VERSION ? {
750
- type: "cmssy:select",
751
- protocolVersion: PROTOCOL_VERSION,
752
- blockId: data.blockId
753
- } : null;
754
- case "cmssy:patch":
755
- return typeof data.blockId === "string" && isObject(data.content) && data.protocolVersion === PROTOCOL_VERSION ? {
756
- type: "cmssy:patch",
757
- blockId: data.blockId,
758
- content: data.content,
759
- protocolVersion: PROTOCOL_VERSION,
760
- ...isObject(data.style) ? { style: data.style } : {},
761
- ...isObject(data.advanced) ? { advanced: data.advanced } : {},
762
- ...typeof data.layoutPosition === "string" ? { layoutPosition: data.layoutPosition } : {}
763
- } : null;
764
- case "cmssy:parent-ready":
765
- return data.protocolVersion === PROTOCOL_VERSION ? { type: "cmssy:parent-ready", protocolVersion: PROTOCOL_VERSION } : null;
766
- case "cmssy:insert":
767
- return typeof data.blockId === "string" && typeof data.blockType === "string" && isObject(data.content) && typeof data.index === "number" && data.protocolVersion === PROTOCOL_VERSION ? {
768
- type: "cmssy:insert",
769
- protocolVersion: PROTOCOL_VERSION,
770
- blockId: data.blockId,
771
- blockType: data.blockType,
772
- content: data.content,
773
- ...isObject(data.style) ? { style: data.style } : {},
774
- ...isObject(data.advanced) ? { advanced: data.advanced } : {},
775
- index: data.index
776
- } : null;
777
- case "cmssy:reorder":
778
- return Array.isArray(data.blockIds) && data.blockIds.every((id) => typeof id === "string") && data.protocolVersion === PROTOCOL_VERSION ? {
779
- type: "cmssy:reorder",
780
- protocolVersion: PROTOCOL_VERSION,
781
- blockIds: data.blockIds
782
- } : null;
783
- case "cmssy:remove":
784
- return typeof data.blockId === "string" && data.protocolVersion === PROTOCOL_VERSION ? {
785
- type: "cmssy:remove",
786
- protocolVersion: PROTOCOL_VERSION,
787
- blockId: data.blockId
788
- } : null;
789
- case "cmssy:drag-over":
790
- return typeof data.y === "number" && data.protocolVersion === PROTOCOL_VERSION ? {
791
- type: "cmssy:drag-over",
792
- protocolVersion: PROTOCOL_VERSION,
793
- y: data.y
794
- } : null;
795
- case "cmssy:drag-end":
796
- return data.protocolVersion === PROTOCOL_VERSION ? { type: "cmssy:drag-end", protocolVersion: PROTOCOL_VERSION } : null;
797
- default:
798
- return null;
799
- }
800
- }
801
-
802
- // src/data/settings-client.ts
803
- async function fetchSiteConfig(config, options = {}) {
804
- const data = await graphqlRequest(
805
- config,
806
- SITE_CONFIG_QUERY,
807
- { workspaceSlug: config.workspaceSlug },
808
- { ...options, public: true, retry: options.retry ?? {} },
809
- "site config query"
810
- );
811
- return data.public?.siteConfig ?? null;
812
- }
813
- async function resolveWorkspaceId(config, options = {}) {
814
- const siteConfig = await fetchSiteConfig(config, options);
815
- if (!siteConfig?.workspaceId) {
816
- throw new Error(
817
- `cmssy: could not resolve workspaceId for "${config.workspaceSlug}"`
818
- );
819
- }
820
- return siteConfig.workspaceId;
821
- }
822
-
823
- // src/data/client.ts
824
- function createCmssyClient(input) {
825
- const config = {
826
- ...input,
827
- apiUrl: resolveApiUrl(input.apiUrl)
828
- };
829
- let cachedWorkspaceId;
830
- let inFlight;
831
- function resolveWorkspaceId2(options) {
832
- if (cachedWorkspaceId) return Promise.resolve(cachedWorkspaceId);
833
- if (!inFlight) {
834
- inFlight = resolveWorkspaceId(config, options).then((id) => {
835
- cachedWorkspaceId = id;
836
- return id;
837
- }).finally(() => {
838
- inFlight = void 0;
839
- });
840
- }
841
- return inFlight;
842
- }
843
- return {
844
- config,
845
- resolveWorkspaceId: resolveWorkspaceId2,
846
- query(document2, variables = {}, options) {
847
- return graphqlRequest(
848
- config,
849
- document2,
850
- variables,
851
- options,
852
- "graphql operation"
853
- );
854
- },
855
- async queryScoped(document2, variables = {}, options = {}) {
856
- const { workspaceId: provided, headers, ...rest } = options;
857
- const workspaceId = provided ?? await resolveWorkspaceId2({ ...rest, headers });
858
- const hasWorkspaceId = variables.workspaceId !== void 0 && variables.workspaceId !== null;
859
- const scopedVariables = /\$workspaceId\b/.test(document2) && !hasWorkspaceId ? { ...variables, workspaceId } : variables;
860
- return graphqlRequest(
861
- config,
862
- document2,
863
- scopedVariables,
864
- { ...rest, headers: { ...headers, "x-workspace-id": workspaceId } },
865
- "graphql operation"
866
- );
867
- }
868
- };
869
- }
870
-
871
- // src/data/resolve-forms.ts
872
- function collectFormIds(blocks, locale, defaultLocale) {
873
- const ids = /* @__PURE__ */ new Set();
874
- for (const block of blocks) {
875
- const content = getBlockContentForLanguage(
876
- block.content,
877
- locale,
878
- defaultLocale
879
- );
880
- const formId = content.formId;
881
- if (typeof formId === "string" && formId.trim()) ids.add(formId);
882
- }
883
- return [...ids];
884
- }
885
- async function resolveForms(config, blocks, locale, defaultLocale, options) {
886
- const ids = collectFormIds(blocks, locale, defaultLocale);
887
- if (ids.length === 0) return {};
888
- const client = createCmssyClient(config);
889
- const entries = await Promise.all(
890
- ids.map(async (id) => {
891
- try {
892
- const data = await client.queryScoped(FORM_QUERY, { formId: id }, options);
893
- return [id, data.public.form.get];
894
- } catch (err) {
895
- if (typeof console !== "undefined") {
896
- console.warn(`[cmssy] failed to resolve form ${id}`, err);
897
- }
898
- return [id, null];
899
- }
900
- })
901
- );
902
- const forms = {};
903
- for (const [id, def] of entries) {
904
- if (def) forms[id] = def;
905
- }
906
- return forms;
907
- }
908
-
909
- // src/data/localize-href.ts
910
- var PROTOCOL_OR_RELATIVE = /^([a-z][a-z0-9+.-]*:|\/\/)/i;
911
- function isExternalHref(href) {
912
- const value = href.trim();
913
- if (!value) return true;
914
- if (value.startsWith("#")) return true;
915
- return PROTOCOL_OR_RELATIVE.test(value);
916
- }
917
- function stripLeadingLocale(path, locale) {
918
- const segments = path.split("/");
919
- const first = segments[1];
920
- if (first && first !== locale.default && locale.enabled.includes(first)) {
921
- segments.splice(1, 1);
922
- const rest = segments.join("/");
923
- return rest === "" ? "/" : rest;
924
- }
925
- return path;
926
- }
927
- function addLocalePrefix(path, target, locale) {
928
- if (target === locale.default) return path;
929
- if (path === "/") return `/${target}`;
930
- return `/${target}${path}`;
931
- }
932
- function localizeHref(href, locale) {
933
- const value = href.trim();
934
- if (isExternalHref(value)) return href;
935
- const boundary = value.search(/[?#]/);
936
- const path = boundary === -1 ? value : value.slice(0, boundary);
937
- const suffix = boundary === -1 ? "" : value.slice(boundary);
938
- if (!path.startsWith("/")) return href;
939
- const bare = stripLeadingLocale(path, locale);
940
- return `${addLocalePrefix(bare, locale.current, locale)}${suffix}`;
941
- }
942
- function buildLocaleSwitchHref(target, pathname, locale) {
943
- const path = pathname && pathname.startsWith("/") ? pathname : "/";
944
- const bare = stripLeadingLocale(path, locale);
945
- return addLocalePrefix(bare, target, locale);
946
- }
947
- var ANCHOR_HREF = /(<a\b(?:"[^"]*"|'[^']*'|[^>])*?\shref=)(["'])(.*?)\2/gi;
948
- function localizeHtmlLinks(html, locale) {
949
- return html.replace(
950
- ANCHOR_HREF,
951
- (_match, prefix, quote, url) => `${prefix}${quote}${localizeHref(url, locale)}${quote}`
952
- );
953
- }
954
224
  function CmssyBlock({
955
225
  block,
956
226
  locale,
@@ -986,4 +256,4 @@ function CmssyBlock({
986
256
  );
987
257
  }
988
258
 
989
- export { CmssyBlock, CmssyRequestError, CmssyServerLayout, CmssyServerPage, DEFAULT_CMSSY_API_URL, FORM_QUERY, MODEL_DEFINITIONS_QUERY, MODEL_RECORDS_QUERY, PROTOCOL_VERSION, SITE_CONFIG_QUERY, SUBMIT_FORM_MUTATION, UnknownBlock, blocksToMeta, blocksToSchemas, buildBlockContext, buildBlockMap, buildLocaleSwitchHref, collectFormIds, createCmssyClient, defineBlock, fetchLayouts, fetchPage, fetchPageById, fetchPageMeta, fetchPages, fetchSiteConfig, fields, getBlockContentForLanguage, graphqlRequest, isProtocolCompatible, localizeHref, localizeHtmlLinks, normalizeOrigin, normalizeSlug, parseEditorMessage, postToEditor, resolveApiUrl, resolveForms, resolvePublicUrl, resolveSiteLocales, resolveWorkspaceId, splitLocaleFromPath };
259
+ export { CmssyBlock, CmssyServerLayout, CmssyServerPage, UnknownBlock, blocksToMeta, blocksToSchemas, buildBlockMap, defineBlock };