@brightsideoy/kama 1.0.0-alpha.31 → 1.0.0-alpha.33

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.
Files changed (78) hide show
  1. package/content/definitions/blocks/form.yaml +4 -4
  2. package/dist/assets/AssetEditor-Vu5cl6lr.js +1 -0
  3. package/dist/assets/CmsFieldTaxonomy-DRTQyTPC.js +1 -0
  4. package/dist/assets/CmsHelp-PptHvDLD.js +1 -0
  5. package/dist/assets/CmsImagePreview-DLYdN_0R.js +1 -0
  6. package/dist/assets/CmsListItem-B6mUoOIw.js +1 -0
  7. package/dist/assets/{preload-helper-BxFQpwa9.css → CmsListItem-BxVd9_U4.css} +1 -1
  8. package/dist/assets/CmsPublisher-CR5-YF5j.js +3 -0
  9. package/dist/assets/EditorSplitPreview-D4gkVuhL.js +1 -0
  10. package/dist/assets/FormsWorkspace-BgGgVexq.css +1 -0
  11. package/dist/assets/FormsWorkspace-DtjET7gT.js +2 -0
  12. package/dist/assets/NodeContextMenu-CP45tlaT.js +1 -0
  13. package/dist/assets/NodeEditor-CPH0rWvI.css +1 -0
  14. package/dist/assets/NodeEditor-otvWuidQ.js +4 -0
  15. package/dist/assets/RteFloatingToolbar-Dvaqq7Vr.js +158 -0
  16. package/dist/assets/RteFloatingToolbar-mfTSuSyi.css +1 -0
  17. package/dist/assets/TrashWorkspace-D42-jimc.js +1 -0
  18. package/dist/assets/{plus-7rv1C56N.js → arrow-right-C5IFL4zO.js} +1 -1
  19. package/dist/assets/clock-ChD9Pw4R.js +1 -0
  20. package/dist/assets/external-link-BR6PVQJR.js +1 -0
  21. package/dist/assets/{globe-TuZP0v6A.js → folder-tree-C9FLiwU1.js} +1 -1
  22. package/dist/assets/globe-Cc-HpKJl.js +1 -0
  23. package/dist/assets/{rotate-ccw-DvjWccJd.js → image-CG70efEv.js} +1 -1
  24. package/dist/assets/index-CGcczV4D.js +14 -0
  25. package/dist/assets/info-CG1rlb3x.js +1 -0
  26. package/dist/assets/plus-8qyrJDmU.js +1 -0
  27. package/dist/assets/preload-helper-Bjj569kd.js +1 -0
  28. package/dist/assets/preload-helper-CsLomdVG.css +1 -0
  29. package/dist/assets/refresh-cw-ldhcYUWO.js +1 -0
  30. package/dist/assets/rotate-ccw-aSXT_vpV.js +1 -0
  31. package/dist/assets/send-CIIg_931.js +1 -0
  32. package/dist/assets/useNodes-CoHDhaah.js +1 -0
  33. package/dist/assets/useTaxonomies-_-T_4Iu-.js +1 -0
  34. package/dist/assets/x-Ds3gRwZk.js +1 -0
  35. package/dist/{dist-DKRU6nhX.js → dist-DHy8KsJ-.js} +4886 -4813
  36. package/dist/index.html +22 -12
  37. package/dist/index.js +4458 -4363
  38. package/dist/schema-compiler.js +1 -1
  39. package/documentation/FORMS.md +72 -34
  40. package/package.json +1 -1
  41. package/templates/astro-starter/src/components/blocks/Form.astro +50 -10
  42. package/templates/astro-starter/src/components/global/Header.astro +5 -7
  43. package/templates/astro-starter/src/components/global/MetaHead.astro +3 -2
  44. package/templates/astro-starter/src/lib/cms-fetch.test.ts +111 -0
  45. package/templates/astro-starter/src/lib/cms-fetch.ts +12 -2
  46. package/templates/astro-starter/src/lib/cms.ts +13 -12
  47. package/templates/astro-starter/src/lib/media/media-proxy.ts +2 -1
  48. package/templates/astro-starter/src/middleware.ts +6 -13
  49. package/templates/astro-starter/src/pages/[...slug].astro +4 -6
  50. package/templates/astro-starter/src/pages/api/forms/[...path].ts +25 -10
  51. package/templates/astro-starter/src/pages/api/load-nodes.ts +2 -1
  52. package/templates/astro-starter/src/pages/api/partials/node-cards.astro +2 -4
  53. package/templates/astro-starter/src/pages/llms-full.txt.ts +7 -7
  54. package/templates/astro-starter/src/pages/llms.txt.ts +5 -6
  55. package/templates/astro-starter/src/pages/partials/footer.astro +2 -4
  56. package/templates/astro-starter/src/pages/partials/nav.astro +3 -5
  57. package/dist/assets/AssetEditor-CAvQEsBT.js +0 -1
  58. package/dist/assets/CmsAccordion-91I5Rx5D.css +0 -1
  59. package/dist/assets/CmsAccordion-BgdaB8QZ.js +0 -1
  60. package/dist/assets/CmsFieldTaxonomy-CNY3-MbD.js +0 -1
  61. package/dist/assets/CmsHelp-DtPeURCv.js +0 -1
  62. package/dist/assets/CmsImagePreview-BhM7S_v8.js +0 -1
  63. package/dist/assets/CmsPublisher-DiQhfPID.js +0 -3
  64. package/dist/assets/EditorSplitPreview-BfGni85I.js +0 -1
  65. package/dist/assets/FormsWorkspace-CGs6eUjz.css +0 -1
  66. package/dist/assets/FormsWorkspace-CUK-y2dR.js +0 -2
  67. package/dist/assets/NodeContextMenu-C5RTK0sr.js +0 -1
  68. package/dist/assets/NodeEditor-C2meZIvc.css +0 -1
  69. package/dist/assets/NodeEditor-C5VQu52a.js +0 -161
  70. package/dist/assets/TrashWorkspace-t0lOrFRK.js +0 -1
  71. package/dist/assets/index-_Tc6Vb8T.js +0 -14
  72. package/dist/assets/preload-helper-BB8Wl1va.js +0 -1
  73. package/dist/assets/send-Bs4eROle.js +0 -1
  74. package/dist/assets/useNodes-D-Vuwq5_.js +0 -1
  75. package/dist/assets/x-DOWbsdzd.js +0 -1
  76. package/dist/nodemailer-Ccic7tRm-Dw2jwzbm.js +0 -7877
  77. package/dist/nodemailer-Ccic7tRm.js +0 -7908
  78. package/dist/rolldown-runtime-B0aSnxlc.js +0 -20
@@ -30,7 +30,7 @@ async function f() {
30
30
  if (n(f)) l = (await import(t(f).href)).compileDefinitions;
31
31
  else if (n(p)) l = (await import(t(p).href)).compileDefinitions;
32
32
  else try {
33
- l = (await import("./dist-DKRU6nhX.js")).compileDefinitions;
33
+ l = (await import("./dist-DHy8KsJ-.js")).compileDefinitions;
34
34
  } catch (e) {
35
35
  console.error("\x1B[31m ✖\x1B[0m \x1B[31mCould not resolve Kama Schema Engine:\x1B[0m", e), process.exit(1);
36
36
  }
@@ -26,23 +26,32 @@ id: contact
26
26
  title: Contact us
27
27
  description: Send our team a message.
28
28
  fields:
29
- - name: email
30
- label: Email
31
- type: email
32
- required: true
29
+ - type: fieldset
30
+ label: Your details
31
+ fields:
32
+ - name: email
33
+ label: Email
34
+ type: email
35
+ required: true
33
36
  - name: message
34
37
  label: Message
35
38
  type: textarea
36
39
  required: true
37
40
  settings:
41
+ submitLabel: Send message
38
42
  successMessage: Thanks for getting in touch.
39
43
  requireTurnstile: false
40
44
  ```
41
45
 
46
+ Fields can be mixed with visual `fieldset` groups. Each group has a `label`
47
+ shown as its legend and a `fields` list; fields inside it are validated and
48
+ included in emails just like other fields. `settings.submitLabel` sets the
49
+ default button text.
50
+
42
51
  ## Add a form to a page
43
52
 
44
- Add the **Form** block to a page and select the form. The block's optional
45
- **Success Message** overrides the message in the form definition. The selected
53
+ Add the **Form** block to a page and select the form. Its optional **Submit
54
+ Button Label** overrides the form's button text. The selected
46
55
  form and block settings are saved as part of the page draft. Draft preview shows
47
56
  the selection after autosave; it does not become public until you publish the
48
57
  page. Form definitions themselves are shared YAML configuration, not page
@@ -51,8 +60,8 @@ displays its ID rather than silently selecting a different form.
51
60
 
52
61
  ## Submissions
53
62
 
54
- All finishers are disabled by default. A valid submission with no finisher
55
- enabled receives the configured success response, but is not saved or emailed.
63
+ Database and email finishers are disabled by default. A valid submission with
64
+ no side-effect finisher enabled is not saved or emailed.
56
65
 
57
66
  Select a form in the Forms sidebar, then use the **Finishers** tab in the main
58
67
  workspace to enable **Save submissions to database**. Saved entries are
@@ -76,9 +85,11 @@ section shows its enabled state while collapsed.
76
85
 
77
86
  ## Finishers
78
87
 
79
- Finishers run after field validation and Turnstile verification, in the order
80
- listed. KAMA registers the `database` and `email` finishers by default. You can
81
- configure finishers on the form or override them on an individual Form block.
88
+ Finishers run after field validation and Turnstile verification. Database,
89
+ email and custom side effects run in the order listed. Success message and
90
+ redirect finishers control the response after those side effects succeed. You
91
+ can configure finishers on the form or override them on an individual Form
92
+ block. Disabled finishers retain their settings when saved and can be re-enabled.
82
93
 
83
94
  ### Configure finishers on a form
84
95
 
@@ -102,21 +113,30 @@ finishers:
102
113
  When finisher settings are saved in the CMS, they override the YAML settings.
103
114
  Registered custom finishers are preserved when built-in settings are edited.
104
115
 
105
- ### Override finishers on a Form block
116
+ Use **Success message** to edit the visitor-facing message with the rich-text
117
+ editor, or disable it to hide the message. **Redirect after submission** lets
118
+ you select a page or HTTP(S) URL and set a delay in seconds. When both are
119
+ enabled, the message appears before the redirect. These finishers are
120
+ independent of email delivery. Existing forms without a message finisher retain
121
+ their legacy `settings.successMessage` and saved block message behavior.
106
122
 
107
- The block editor can replace the form's complete finisher list. It supports
108
- enabling or disabling database storage, adding or removing email finishers, and
109
- setting their recipient, sender email, subject, sender name, reply-to, and
110
- message templates. Registered custom finishers can also be added, enabled,
111
- removed, or edited as JSON. Email transport is configured once for the KAMA
112
- package environment, not per form or block.
123
+ ### Override finishers on a Form block
113
124
 
114
- Block overrides are saved with the page. On submission, KAMA reloads and
115
- validates the published finisher configuration from the database instead of
116
- trusting settings sent by the visitor. Transport credentials cannot be changed
117
- in the block editor. Sender addresses must be authorized by the configured
118
- email provider. Custom finisher JSON is validated for size and type; each
119
- custom handler must validate its own settings.
125
+ The block editor lists the form's finishers individually. Select a finisher to
126
+ override it for that block; unselected finishers continue to use the form's
127
+ current settings. An override has its own enable/disable control and keeps its
128
+ settings when disabled. Built-in finishers use the same named settings as the
129
+ form editor. Registered custom finishers can also be overridden or added at the
130
+ block level, enabled or disabled, and edited as JSON.
131
+
132
+ Block overrides are saved with the page and merged with the form's current
133
+ finishers on submission. KAMA validates the published block configuration
134
+ instead of trusting settings sent by the visitor. Transport credentials cannot
135
+ be changed in the block editor. Sender addresses must be authorized by the
136
+ configured email provider. Custom finisher JSON is validated for size and
137
+ type; each custom handler must validate its own settings. Existing blocks with
138
+ legacy full-list overrides retain that behavior until edited in the block
139
+ editor.
120
140
 
121
141
  ### Add a custom finisher
122
142
 
@@ -200,10 +220,18 @@ email field. Keep the sender address fixed; use `replyToField` when replies
200
220
  should go to the submitter. Subject text and optional `text` or `html` bodies
201
221
  support `{{field}}` placeholders. Interpolated HTML values are escaped.
202
222
 
203
- If no body template is set, the message includes all submitted fields.
223
+ The rich-text email template editor starts with a simple template containing
224
+ the form title and a `{{fieldName}}` placeholder for each field. Edit this
225
+ template as needed. If no body template is set, the generated default includes
226
+ all submitted fields.
204
227
  `FORMS_EMAIL_FROM` is the sender fallback, and `FORMS_EMAIL_FROM_NAME` provides
205
228
  an optional deployment-wide sender-name fallback.
206
229
 
230
+ Rich-text templates and success messages are authored HTML: grant form and
231
+ block editing privileges only to trusted CMS users. With JavaScript disabled,
232
+ the Astro starter shows explicit messages and redirects on a minimal response
233
+ page, with a link back or onward.
234
+
207
235
  If an email finisher fails, the submission fails and KAMA does not return a
208
236
  success response. Email delivery and database writes cannot be rolled back
209
237
  atomically, so earlier finishers may already have run. Retrying can repeat
@@ -231,15 +259,19 @@ production form; configure real keys for deployed environments.
231
259
 
232
260
  When available, the Astro starter uses the `CMS_WORKER` service binding for CMS
233
261
  API and `/media/*` requests. Form submissions go through the same-origin
234
- `/api/forms/:formId/submissions` proxy. Without the binding, it uses
235
- `PUBLIC_API_URL` server-side; local development defaults to the CMS Worker at
236
- `http://127.0.0.1:8787`.
237
-
238
- For local Astro development, run the CMS Worker on port `8787` as well as the
239
- Astro site. If the local service binding reports that its target Worker is not
240
- running, page and media proxies fall back to `127.0.0.1:8787`. Keep the site's
241
- and CMS Worker's `FRONTEND_API_SECRET` values matched in their local secret
242
- files. Never expose a server-only API secret in browser code.
262
+ `/api/forms/:formId/submissions` proxy. Configure `PUBLIC_API_URL` (or
263
+ `PUBLIC_CMS_URL`) on the Astro site, even when using a service binding.
264
+ There is no implicit CMS URL.
265
+
266
+ Set the URL to the intended CMS instance in both development and deployment
267
+ (for example, `http://127.0.0.1:8686` for a Node server on that port). If a
268
+ local service binding reports its target Worker is not running, form, page and
269
+ middleware media requests retry only at the configured loopback URL. Keep the
270
+ site's and CMS Worker's `FRONTEND_API_SECRET` values matched in their local
271
+ secret files. Never expose a server-only API secret in browser code. Astro can
272
+ embed public environment variables at build time, so rebuild after changing
273
+ them. Use a production build on a VPS: Astro development mode enables
274
+ Turnstile test keys.
243
275
 
244
276
  ### Draft preview iframe
245
277
 
@@ -259,3 +291,9 @@ loopback.
259
291
  | `GET` | `/api/cms/forms/:formId/submissions` | Fetch saved submissions and field labels. |
260
292
  | `DELETE` | `/api/cms/forms/:formId/submissions/:submissionId` | Delete one saved submission. |
261
293
  | `DELETE` | `/api/cms/forms/:formId/submissions` | Delete selected submissions; send `{ "ids": [1, 2] }` as JSON. |
294
+
295
+ The public definition includes flattened `fields` for compatibility and
296
+ `layout` for rendering fieldsets. Successful submissions may include
297
+ `notification` (HTML, or `null` when explicitly disabled) and `redirect`
298
+ (`{ url, delay }`, with delay in seconds). The existing `message` remains
299
+ available when no notification finisher is configured.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brightsideoy/kama",
3
- "version": "1.0.0-alpha.31",
3
+ "version": "1.0.0-alpha.33",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1,11 +1,13 @@
1
1
  ---
2
2
  // src/components/blocks/Form.astro
3
- import { fetchCmsRequest } from '../../lib/cms-fetch';
3
+ import { fetchCmsRequest, getCmsApiUrl } from '../../lib/cms-fetch';
4
+ import { getChannelId } from '../../lib/cms';
4
5
 
5
6
  interface Props {
6
7
  data: {
7
8
  formId: string;
8
9
  successMessage?: string;
10
+ submitLabel?: string;
9
11
  };
10
12
  blockId: number | string;
11
13
  contentId: number | string;
@@ -16,11 +18,6 @@ const formId = data?.formId;
16
18
 
17
19
  const safeEnv = (Astro.locals as any).safeEnv || {};
18
20
  const cmsWorker = safeEnv.CMS_WORKER;
19
- const kamaApiUrl = String(
20
- import.meta.env.DEV && !cmsWorker
21
- ? 'http://localhost:8787'
22
- : import.meta.env.PUBLIC_API_URL || safeEnv.PUBLIC_API_URL || 'http://localhost:8787'
23
- ).replace(/\/$/, '');
24
21
  const configuredTurnstileSiteKey = String(
25
22
  import.meta.env.PUBLIC_TURNSTILE_SITE_KEY || safeEnv.PUBLIC_TURNSTILE_SITE_KEY || ''
26
23
  ).trim();
@@ -32,6 +29,7 @@ const turnstileSiteKey = configuredTurnstileSiteKey || (
32
29
  let schema = null;
33
30
  if (formId) {
34
31
  try {
32
+ const kamaApiUrl = getCmsApiUrl(safeEnv);
35
33
  const schemaUrl = `${kamaApiUrl}/api/v1/forms/${encodeURIComponent(formId)}`;
36
34
  const schemaRequest = new Request(schemaUrl, { headers: { Accept: 'application/json' } });
37
35
  const res = await fetchCmsRequest(schemaRequest, cmsWorker);
@@ -87,7 +85,33 @@ const submissionMessage = Astro.url.searchParams.get('formMessage');
87
85
  method="post"
88
86
  action={`/api/forms/${encodeURIComponent(formId)}/submissions`}
89
87
  >
90
- {schema.fields?.map((field: any) => (
88
+ <input type="hidden" name="_kamaFinisherBlockId" value={String(blockId)} />
89
+ <input type="hidden" name="_kamaFinisherContentId" value={String(contentId)} />
90
+ <input type="hidden" name="_kamaChannelId" value={safeEnv.PUBLIC_CHANNEL_ID || getChannelId()} />
91
+ <input type="hidden" name="_kamaSuccessMessage" value={data?.successMessage || ''} />
92
+ {(schema.layout || schema.fields)?.map((field: any) => field.type === 'fieldset' ? (
93
+ <fieldset class="form-fieldset">
94
+ {field.label && <legend>{field.label}</legend>}
95
+ {field.fields?.map((item: any) => (
96
+ <div class="form-group">
97
+ <label for={`field-${item.name}`}>
98
+ {item.label}
99
+ {item.required && <span class="required" aria-hidden="true"> *</span>}
100
+ </label>
101
+ {item.type === 'textarea' ? (
102
+ <textarea id={`field-${item.name}`} name={item.name} placeholder={item.placeholder || ''} required={item.required} rows="4" />
103
+ ) : item.type === 'select' ? (
104
+ <select id={`field-${item.name}`} name={item.name} required={item.required}>
105
+ <option value="" disabled selected>{item.placeholder || 'Select...'}</option>
106
+ {item.options?.map((opt: any) => <option value={opt.value}>{opt.label}</option>)}
107
+ </select>
108
+ ) : (
109
+ <input type={item.type || 'text'} id={`field-${item.name}`} name={item.name} placeholder={item.placeholder || ''} required={item.required} />
110
+ )}
111
+ </div>
112
+ ))}
113
+ </fieldset>
114
+ ) : (
91
115
  <div class="form-group">
92
116
  <label for={`field-${field.name}`}>
93
117
  {field.label}
@@ -122,7 +146,7 @@ const submissionMessage = Astro.url.searchParams.get('formMessage');
122
146
  </p>
123
147
  )}
124
148
 
125
- <button type="submit" class="submit-btn">Submit</button>
149
+ <button type="submit" class="submit-btn">{data?.submitLabel || schema.settings?.submitLabel || 'Submit'}</button>
126
150
  </form>
127
151
  </div>
128
152
  ) : (
@@ -155,6 +179,12 @@ const submissionMessage = Astro.url.searchParams.get('formMessage');
155
179
  min-width: 0;
156
180
  }
157
181
 
182
+ .form-fieldset {
183
+ display: grid;
184
+ gap: 1.25rem;
185
+ min-width: 0;
186
+ }
187
+
158
188
  .form-group label {
159
189
  color: #0f172a;
160
190
  font-weight: 600;
@@ -297,10 +327,20 @@ const submissionMessage = Astro.url.searchParams.get('formMessage');
297
327
  throw new Error(result.error || 'Form submission failed.');
298
328
  }
299
329
 
300
- successBox.textContent = container.getAttribute('data-success-message') || result.message || 'Form submitted successfully!';
301
- successBox.style.display = 'block';
330
+ if (typeof result.notification === 'string') {
331
+ successBox.innerHTML = result.notification;
332
+ successBox.style.display = 'block';
333
+ } else if (result.notification !== null) {
334
+ successBox.textContent = container.getAttribute('data-success-message') || result.message || 'Form submitted successfully!';
335
+ successBox.style.display = 'block';
336
+ }
302
337
  form.reset();
303
338
  if (window.turnstile) window.turnstile.reset();
339
+ if (result.redirect?.url) {
340
+ const target = new URL(result.redirect.url, window.location.href);
341
+ if (!['http:', 'https:'].includes(target.protocol)) throw new Error('Invalid redirect destination.');
342
+ window.setTimeout(() => window.location.assign(target.href), Math.max(0, Number(result.redirect.delay) || 0) * 1000);
343
+ }
304
344
  } catch (error) {
305
345
  errorBox.textContent = error instanceof Error ? error.message : 'Form submission failed.';
306
346
  errorBox.style.display = 'block';
@@ -5,6 +5,7 @@ import NavigationMenu from "@/components/global/NavigationMenu.astro";
5
5
  import KamaImage from "@/components/ui/KamaImage.astro";
6
6
  import { getTree, getTreeId, getChannel, getChannelId } from "@/lib/cms";
7
7
  import type { TreeNode } from "@/lib/cms";
8
+ import { getCmsApiUrl } from "@/lib/cms-fetch";
8
9
 
9
10
  interface Props {
10
11
  node?: Record<string, any>;
@@ -25,10 +26,7 @@ const customFetch = (input: RequestInfo | URL, init?: RequestInit) => {
25
26
  let urlStr = input instanceof URL ? input.toString() : String(input);
26
27
 
27
28
  if (urlStr.startsWith("/")) {
28
- const baseUrl =
29
- import.meta.env.PUBLIC_API_URL ||
30
- safeEnv.PUBLIC_API_URL ||
31
- "http://127.0.0.1:8787";
29
+ const baseUrl = getCmsApiUrl(safeEnv);
32
30
  urlStr = `${baseUrl}${urlStr}`;
33
31
  }
34
32
 
@@ -49,13 +47,13 @@ let channelData: Record<string, any> | null = null;
49
47
  try {
50
48
  if (!rawTree || rawTree.length === 0) {
51
49
  const [fetchedChannel, fetchedTree] = await Promise.all([
52
- getChannel(channelId, customFetch),
53
- getTree(treeId, channelId, customFetch),
50
+ getChannel(channelId, customFetch, safeEnv),
51
+ getTree(treeId, channelId, customFetch, safeEnv),
54
52
  ]);
55
53
  channelData = fetchedChannel;
56
54
  rawTree = fetchedTree || [];
57
55
  } else {
58
- channelData = await getChannel(channelId, customFetch);
56
+ channelData = await getChannel(channelId, customFetch, safeEnv);
59
57
  }
60
58
  } catch (e) {
61
59
  console.error("[Header] Failed to load layout data:", e);
@@ -4,6 +4,7 @@
4
4
  import type { ContentBlock } from "@/lib/cms";
5
5
  import { getChannel, getChannelId } from "@/lib/cms";
6
6
  import { getImageUri } from "@/lib/media/media-url";
7
+ import { getCmsApiUrl } from "@/lib/cms-fetch";
7
8
 
8
9
  interface Props {
9
10
  node: Record<string, any>;
@@ -34,7 +35,7 @@ const customFetch = (input: RequestInfo | URL, init?: RequestInit) => {
34
35
  let urlStr = input instanceof URL ? input.toString() : String(input);
35
36
 
36
37
  if (urlStr.startsWith("/")) {
37
- const baseUrl = import.meta.env.PUBLIC_API_URL || safeEnv.PUBLIC_API_URL || "http://127.0.0.1:8787";
38
+ const baseUrl = getCmsApiUrl(safeEnv);
38
39
  urlStr = `${baseUrl}${urlStr}`;
39
40
  }
40
41
 
@@ -47,7 +48,7 @@ const customFetch = (input: RequestInfo | URL, init?: RequestInit) => {
47
48
  };
48
49
 
49
50
  // 🎯 Fetch Global Channel Metadata
50
- const channel = await getChannel(getChannelId(), customFetch);
51
+ const channel = await getChannel(getChannelId(), customFetch, safeEnv);
51
52
 
52
53
  // 🎯 Language Cascade Final Resolution:
53
54
  // Prop / Node Language -> Channel Default -> Undefined
@@ -0,0 +1,111 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { createServer } from 'vite';
4
+
5
+ async function createTestServer(apiUrl: string, cmsUrl = '') {
6
+ return createServer({
7
+ configFile: false,
8
+ define: {
9
+ 'import.meta.env.PUBLIC_API_URL': JSON.stringify(apiUrl),
10
+ 'import.meta.env.PUBLIC_CMS_URL': JSON.stringify(cmsUrl),
11
+ },
12
+ server: { middlewareMode: true, hmr: false, watch: { ignored: ['**'] } },
13
+ appType: 'custom',
14
+ });
15
+ }
16
+
17
+ test('form requests use the configured CMS in development', async () => {
18
+ const server = await createTestServer('http://127.0.0.1:8686/');
19
+ const originalFetch = globalThis.fetch;
20
+ try {
21
+ const { getCmsApiUrl } = await server.ssrLoadModule('/templates/astro-starter/src/lib/cms-fetch.ts');
22
+ const { POST } = await server.ssrLoadModule('/templates/astro-starter/src/pages/api/forms/[...path].ts');
23
+ assert.equal(getCmsApiUrl(), 'http://127.0.0.1:8686');
24
+
25
+ let forwarded: Request | undefined;
26
+ globalThis.fetch = async (input) => {
27
+ assert.ok(input instanceof Request);
28
+ forwarded = input;
29
+ return Response.json({ success: true });
30
+ };
31
+ const response = await POST({
32
+ params: { path: 'contact/submissions' },
33
+ request: new Request('http://localhost:4322/api/forms/contact/submissions', {
34
+ method: 'POST',
35
+ headers: { 'content-type': 'application/json' },
36
+ body: JSON.stringify({ email: 'test@example.com' }),
37
+ }),
38
+ locals: {},
39
+ });
40
+ assert.equal(response.status, 200);
41
+ assert.equal(forwarded?.url, 'http://127.0.0.1:8686/api/v1/forms/contact/submissions');
42
+ assert.deepEqual(await forwarded?.json(), { email: 'test@example.com' });
43
+ } finally {
44
+ globalThis.fetch = originalFetch;
45
+ await server.close();
46
+ }
47
+ });
48
+
49
+ test('form requests require a configured CMS URL', async () => {
50
+ const server = await createTestServer('');
51
+ const originalApiUrl = process.env.PUBLIC_API_URL;
52
+ const originalCmsUrl = process.env.PUBLIC_CMS_URL;
53
+ const originalConsoleError = console.error;
54
+ delete process.env.PUBLIC_API_URL;
55
+ delete process.env.PUBLIC_CMS_URL;
56
+ try {
57
+ const { getCmsApiUrl } = await server.ssrLoadModule('/templates/astro-starter/src/lib/cms-fetch.ts');
58
+ const { getTree } = await server.ssrLoadModule('/templates/astro-starter/src/lib/cms.ts');
59
+ const { POST } = await server.ssrLoadModule('/templates/astro-starter/src/pages/api/forms/[...path].ts');
60
+ assert.equal(getCmsApiUrl({ PUBLIC_API_URL: 'http://127.0.0.1:8686/' }), 'http://127.0.0.1:8686');
61
+ assert.equal(getCmsApiUrl({ PUBLIC_CMS_URL: 'http://127.0.0.1:8686/' }), 'http://127.0.0.1:8686');
62
+ assert.throws(() => getCmsApiUrl(), /Set PUBLIC_API_URL or PUBLIC_CMS_URL/);
63
+ let treeUrl = '';
64
+ await getTree('main-tree', 'site', async (input: RequestInfo | URL) => {
65
+ treeUrl = String(input);
66
+ return Response.json({ items: [] });
67
+ }, { PUBLIC_API_URL: 'http://127.0.0.1:8686' });
68
+ assert.equal(treeUrl, 'http://127.0.0.1:8686/api/v1/tree/main-tree?channelId=site');
69
+
70
+ let loggedError: unknown;
71
+ console.error = (_message, error) => { loggedError = error; };
72
+ const response = await POST({
73
+ params: { path: 'contact/submissions' },
74
+ request: new Request('http://localhost:4322/api/forms/contact/submissions', { method: 'POST' }),
75
+ locals: {},
76
+ });
77
+ assert.equal(response.status, 502);
78
+ assert.match(String(loggedError), /Set PUBLIC_API_URL or PUBLIC_CMS_URL/);
79
+ } finally {
80
+ console.error = originalConsoleError;
81
+ if (originalApiUrl !== undefined) process.env.PUBLIC_API_URL = originalApiUrl;
82
+ if (originalCmsUrl !== undefined) process.env.PUBLIC_CMS_URL = originalCmsUrl;
83
+ await server.close();
84
+ }
85
+ });
86
+
87
+ test('a missing local service binding retries only the configured loopback URL', async () => {
88
+ const server = await createTestServer('');
89
+ const originalFetch = globalThis.fetch;
90
+ try {
91
+ const { fetchCmsRequest } = await server.ssrLoadModule('/templates/astro-starter/src/lib/cms-fetch.ts');
92
+ const binding = {
93
+ fetch: async () => new Response('Worker "cms" not found. Make sure it is running locally.', { status: 503 }),
94
+ };
95
+ const calls: string[] = [];
96
+ globalThis.fetch = async (input) => {
97
+ assert.ok(input instanceof Request);
98
+ calls.push(input.url);
99
+ return new Response('ok');
100
+ };
101
+ const local = await fetchCmsRequest(new Request('http://127.0.0.1:8686/api/v1/forms/contact'), binding);
102
+ assert.equal(local.status, 200);
103
+ assert.deepEqual(calls, ['http://127.0.0.1:8686/api/v1/forms/contact']);
104
+ const remote = await fetchCmsRequest(new Request('https://cms.example.com/api/v1/forms/contact'), binding);
105
+ assert.equal(remote.status, 503);
106
+ assert.equal(calls.length, 1);
107
+ } finally {
108
+ globalThis.fetch = originalFetch;
109
+ await server.close();
110
+ }
111
+ });
@@ -1,3 +1,13 @@
1
+ export function getCmsApiUrl(env: { PUBLIC_API_URL?: string; PUBLIC_CMS_URL?: string } = {}): string {
2
+ const url = (
3
+ import.meta.env.PUBLIC_API_URL || env.PUBLIC_API_URL ||
4
+ import.meta.env.PUBLIC_CMS_URL || env.PUBLIC_CMS_URL ||
5
+ (typeof process !== 'undefined' && (process.env.PUBLIC_API_URL || process.env.PUBLIC_CMS_URL))
6
+ );
7
+ if (!url || !url.trim()) throw new Error('Set PUBLIC_API_URL or PUBLIC_CMS_URL to the CMS URL.');
8
+ return url.trim().replace(/\/+$/, '');
9
+ }
10
+
1
11
  export async function fetchCmsRequest(
2
12
  request: Request,
3
13
  cmsWorker: { fetch: (request: Request) => Promise<Response> } | undefined,
@@ -17,6 +27,6 @@ export async function fetchCmsRequest(
17
27
  return response;
18
28
  }
19
29
 
20
- const localUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, "http://127.0.0.1:8787");
21
- return fetch(new Request(localUrl, fallbackRequest));
30
+ if (!['localhost', '127.0.0.1', '[::1]'].includes(requestUrl.hostname)) return response;
31
+ return fetch(fallbackRequest);
22
32
  }
@@ -1,5 +1,7 @@
1
1
  // src/lib/cms.ts
2
2
 
3
+ import { getCmsApiUrl } from './cms-fetch';
4
+
3
5
  export interface TreeNode {
4
6
  id: number;
5
7
  treeNodeId: number;
@@ -78,12 +80,8 @@ export interface ChannelResponse {
78
80
  /**
79
81
  * Resolves base CMS URL across runtime environments safely via Astro
80
82
  */
81
- export function getCmsUrl(): string {
82
- const url =
83
- import.meta.env.PUBLIC_API_URL ||
84
- import.meta.env.PUBLIC_CMS_URL ||
85
- 'http://localhost:8787';
86
- return url.replace(/\/+$/, '');
83
+ export function getCmsUrl(env: { PUBLIC_API_URL?: string; PUBLIC_CMS_URL?: string } = {}): string {
84
+ return getCmsApiUrl(env);
87
85
  }
88
86
 
89
87
  /**
@@ -114,9 +112,10 @@ function getAuthHeaders(): Record<string, string> {
114
112
  */
115
113
  export async function getChannel(
116
114
  channelKeyOrId: string = getChannelId(),
117
- customFetch: typeof fetch = fetch
115
+ customFetch: typeof fetch = fetch,
116
+ env: { PUBLIC_API_URL?: string; PUBLIC_CMS_URL?: string } = {}
118
117
  ): Promise<ChannelResponse | null> {
119
- const baseUrl = getCmsUrl();
118
+ const baseUrl = getCmsUrl(env);
120
119
  const requestUrl = `${baseUrl}/api/v1/channel/${channelKeyOrId}`;
121
120
 
122
121
  try {
@@ -146,9 +145,10 @@ export async function getChannel(
146
145
  export async function getTree(
147
146
  treeKeyOrId: string = getTreeId(),
148
147
  channel: string | number = getChannelId(),
149
- customFetch: typeof fetch = fetch
148
+ customFetch: typeof fetch = fetch,
149
+ env: { PUBLIC_API_URL?: string; PUBLIC_CMS_URL?: string } = {}
150
150
  ): Promise<TreeNode[]> {
151
- const baseUrl = getCmsUrl();
151
+ const baseUrl = getCmsUrl(env);
152
152
  const requestUrl = `${baseUrl}/api/v1/tree/${treeKeyOrId}?channelId=${channel}`;
153
153
 
154
154
  try {
@@ -180,12 +180,13 @@ export async function getNodeByPath(
180
180
  path: string,
181
181
  channel: string | number = getChannelId(),
182
182
  preview = false,
183
- customFetch: typeof fetch = fetch
183
+ customFetch: typeof fetch = fetch,
184
+ env: { PUBLIC_API_URL?: string; PUBLIC_CMS_URL?: string } = {}
184
185
  ): Promise<NodeResponse | null> {
185
186
  // 🎯 We keep 'index' as the fallback string for Hono routing compatibility,
186
187
  // because the backend dynamically intercepts 'index' and returns the channelRoot!
187
188
  const cleanPath = path.replace(/^\/+|\/+$/g, '') || 'index';
188
- const baseUrl = getCmsUrl();
189
+ const baseUrl = getCmsUrl(env);
189
190
  const requestUrl = `${baseUrl}/api/v1/node/${cleanPath}?channelId=${channel}&preview=${preview}`;
190
191
 
191
192
  try {
@@ -1,6 +1,7 @@
1
1
  // src/lib/media/media-proxy.ts
2
2
 
3
3
  import type { APIContext } from "astro";
4
+ import { getCmsApiUrl } from "../cms-fetch";
4
5
 
5
6
  export function getMimeType(filePath: string): string {
6
7
  const ext = filePath.split(".").pop()?.toLowerCase();
@@ -108,7 +109,7 @@ export async function handleMediaProxy({ request, params, url, locals }: APICont
108
109
  }
109
110
  // B. Local Dev Mode (Standard HTTP Fetch to local Hono Server)
110
111
  else {
111
- const cmsUrl = import.meta.env.PUBLIC_CMS_URL || 'http://localhost:8787';
112
+ const cmsUrl = getCmsApiUrl(workerEnv);
112
113
  const targetUrl = `${cmsUrl}${url.pathname}${url.search}`;
113
114
 
114
115
  // Forward request headers (like Accept for WebP/AVIF negotiation)
@@ -1,7 +1,7 @@
1
1
  // src/middleware.ts
2
2
 
3
3
  import { defineMiddleware } from "astro:middleware";
4
- import { fetchCmsRequest } from "./lib/cms-fetch";
4
+ import { fetchCmsRequest, getCmsApiUrl } from "./lib/cms-fetch";
5
5
 
6
6
  /**
7
7
  * Safely extracts environment variables across Astro 7, Node.js, and Cloudflare Workers
@@ -20,7 +20,7 @@ async function getSafeEnv(locals: any): Promise<Record<string, any>> {
20
20
  // 2. Safe check for locals.runtime / cfContext (Local Node.js / Hono)
21
21
  const runtime = locals?.runtime || locals?.cfContext;
22
22
  if (runtime && typeof runtime === "object") {
23
- if ("CMS_WORKER" in runtime || "PUBLIC_API_URL" in runtime) {
23
+ if ("CMS_WORKER" in runtime || "PUBLIC_API_URL" in runtime || "PUBLIC_CMS_URL" in runtime) {
24
24
  return runtime;
25
25
  }
26
26
 
@@ -105,16 +105,7 @@ export const onRequest = defineMiddleware(async (context, next) => {
105
105
 
106
106
  // 2. Cold Fetch: Pass to CMS worker for AVIF transformation
107
107
  const cmsWorker = workerEnv?.CMS_WORKER;
108
- const envApiUrl = import.meta.env?.PUBLIC_API_URL || import.meta.env?.PUBLIC_CMS_URL;
109
- const workerApiUrl = workerEnv?.PUBLIC_API_URL || workerEnv?.PUBLIC_CMS_URL;
110
- const localDevApiUrl = "http://127.0.0.1:8787";
111
- const fallbackApiUrl = isDev ? localDevApiUrl : "https://kama.kamaengine.com";
112
- const baseApiUrl = String(
113
- isDev && !cmsWorker
114
- ? localDevApiUrl
115
- : workerApiUrl || envApiUrl || fallbackApiUrl
116
- );
117
- const cleanApiUrl = baseApiUrl.endsWith("/") ? baseApiUrl.slice(0, -1) : baseApiUrl;
108
+ const cleanApiUrl = getCmsApiUrl(workerEnv);
118
109
 
119
110
  const mediaUrl = `${cleanApiUrl}${pathname}${context.url.search}`;
120
111
  const mediaReq = new Request(mediaUrl, { headers: context.request.headers });
@@ -537,7 +528,9 @@ export const onRequest = defineMiddleware(async (context, next) => {
537
528
  response.headers.set("X-Content-Type-Options", "nosniff");
538
529
 
539
530
  // 🎯 Extract origin from env dynamically
540
- const cmsUrl = workerEnv?.PUBLIC_CMS_URL || workerEnv?.PUBLIC_API_URL || "http://localhost:8787";
531
+ const cmsUrl = workerEnv?.PUBLIC_CMS_URL || import.meta.env.PUBLIC_CMS_URL
532
+ || (typeof process !== "undefined" && process.env.PUBLIC_CMS_URL)
533
+ || getCmsApiUrl(workerEnv);
541
534
  let cmsOrigin = "";
542
535
  try {
543
536
  cmsOrigin = new URL(cmsUrl).origin;