@hyperspan/framework 1.0.19 → 1.0.21

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperspan/framework",
3
- "version": "1.0.19",
3
+ "version": "1.0.21",
4
4
  "description": "Hyperspan Web Framework",
5
5
  "main": "src/server.ts",
6
6
  "types": "src/server.ts",
@@ -99,7 +99,7 @@ function formSubmitToRoute(e: Event, form: HTMLFormElement, opts: TFormSubmitOpt
99
99
  }
100
100
 
101
101
  fetch(formUrl, { body: formData, method, headers })
102
- .then((res: Response) => {
102
+ .then(async (res: Response) => {
103
103
  // Look for special header that indicates a redirect.
104
104
  // fetch() automatically follows 3xx redirects, so we need to handle this manually to redirect the user to the full page
105
105
  if (res.headers.has('X-Redirect-Location')) {
@@ -109,21 +109,20 @@ function formSubmitToRoute(e: Event, form: HTMLFormElement, opts: TFormSubmitOpt
109
109
 
110
110
  // If the new URL is the same as the current URL, we can just fetch the new HTML and apply it
111
111
  if (resolved.pathname === window.location.pathname) {
112
- return fetch(resolved.href, {
112
+ const pageRes = await fetch(resolved.href, {
113
113
  headers: { Accept: 'text/html' },
114
- })
115
- .then((r) => r.text());
114
+ });
115
+ await consumeStreamingHtmlResponse(pageRes, applyResponseHtml);
116
+ return;
116
117
  }
117
118
 
118
119
  // If the new URL is different, we need to redirect the user to the new URL
119
120
  window.location.assign(newUrl);
120
121
  }
121
- return '';
122
+ return;
122
123
  }
123
124
 
124
- return res.text();
125
- })
126
- .then((content: string) => {
125
+ const content = await res.text();
127
126
  // No content = DO NOTHING (redirect or something else happened)
128
127
  if (!content) {
129
128
  return;
@@ -134,4 +133,94 @@ function formSubmitToRoute(e: Event, form: HTMLFormElement, opts: TFormSubmitOpt
134
133
  .catch((error) => {
135
134
  console.error('[Hyperspan] Error submitting form action:', error);
136
135
  });
136
+ }
137
+
138
+ /** Streaming async chunks use template ids ending in `_content`. */
139
+ const STREAM_CHUNK_MARKER = /<template id="[^"]+_content">/;
140
+
141
+ function splitInitialStreamHtml(html: string): { initial: string; streamTail: string | null } {
142
+ const match = STREAM_CHUNK_MARKER.exec(html);
143
+ if (!match || match.index === 0) {
144
+ return { initial: html, streamTail: null };
145
+ }
146
+ return {
147
+ initial: html.slice(0, match.index),
148
+ streamTail: html.slice(match.index),
149
+ };
150
+ }
151
+
152
+ /** Append streamed HTML to body and run any inline scripts (e.g. window._hsc.push). */
153
+ function appendHtmlToBody(html: string) {
154
+ if (!html) {
155
+ return;
156
+ }
157
+
158
+ const template = document.createElement('template');
159
+ template.innerHTML = html;
160
+ const scripts: HTMLScriptElement[] = [];
161
+ template.content.querySelectorAll('script').forEach((script) => {
162
+ scripts.push(script);
163
+ script.remove();
164
+ });
165
+ document.body.appendChild(template.content);
166
+ for (const script of scripts) {
167
+ const executable = document.createElement('script');
168
+ if (script.src) {
169
+ executable.src = script.src;
170
+ } else {
171
+ executable.textContent = script.textContent;
172
+ }
173
+ document.body.appendChild(executable);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Read a (possibly streaming) HTML response: Idiomorph the initial page HTML, then append
179
+ * later stream chunks to document.body so streaming scripts run and placeholders resolve.
180
+ */
181
+ async function consumeStreamingHtmlResponse(
182
+ res: Response,
183
+ applyInitialHtml: (html: string) => void
184
+ ) {
185
+ const body = res.body;
186
+ if (!body) {
187
+ const text = await res.text();
188
+ if (text) {
189
+ applyInitialHtml(text);
190
+ }
191
+ return;
192
+ }
193
+
194
+ const reader = body.getReader();
195
+ const decoder = new TextDecoder();
196
+ let isFirstChunk = true;
197
+
198
+ function processChunk(html: string) {
199
+ if (!html) {
200
+ return;
201
+ }
202
+
203
+ if (isFirstChunk) {
204
+ isFirstChunk = false;
205
+ const { initial, streamTail } = splitInitialStreamHtml(html);
206
+ if (initial) {
207
+ applyInitialHtml(initial);
208
+ }
209
+ if (streamTail) {
210
+ appendHtmlToBody(streamTail);
211
+ }
212
+ return;
213
+ }
214
+
215
+ appendHtmlToBody(html);
216
+ }
217
+
218
+ while (true) {
219
+ const { done, value } = await reader.read();
220
+ if (done) {
221
+ processChunk(decoder.decode());
222
+ break;
223
+ }
224
+ processChunk(decoder.decode(value, { stream: true }));
225
+ }
137
226
  }
package/src/utils.test.ts CHANGED
@@ -65,6 +65,40 @@ describe('formDataToJSON', () => {
65
65
  colors: ['red', 'green', 'blue'],
66
66
  });
67
67
  });
68
+
69
+ test('formDataToJSON handles array of objects with numeric keys', () => {
70
+ const formData = new FormData();
71
+ formData.append('contact[0][name]', 'John');
72
+ formData.append('contact[0][email]', 'john@example.com');
73
+ formData.append('contact[1][name]', 'Jane');
74
+ formData.append('contact[1][email]', 'jane@example.com');
75
+
76
+ const result = formDataToJSON(formData);
77
+
78
+ expect(result).toEqual({
79
+ contact: [
80
+ { name: 'John', email: 'john@example.com' },
81
+ { name: 'Jane', email: 'jane@example.com' },
82
+ ],
83
+ } as any);
84
+ });
85
+
86
+ test('formDataToJSON keeps object when keys are mixed numeric and text', () => {
87
+ const formData = new FormData();
88
+ formData.append('contact[0][name]', 'John');
89
+ formData.append('contact[0][email]', 'john@example.com');
90
+ formData.append('contact[label]', 'Primary');
91
+
92
+ const result = formDataToJSON(formData);
93
+
94
+ // Not ALL keys are numeric ("label"), so it must stay an object - not an array
95
+ expect(result).toEqual({
96
+ contact: {
97
+ '0': { name: 'John', email: 'john@example.com' },
98
+ label: 'Primary',
99
+ },
100
+ } as any);
101
+ });
68
102
  });
69
103
 
70
104
  describe('parsePath', () => {
package/src/utils.ts CHANGED
@@ -131,11 +131,38 @@ export function formDataToJSON(formData: FormData | URLSearchParams): Record<str
131
131
  }
132
132
  };
133
133
 
134
+ /**
135
+ * Recursively converts objects whose keys are ALL numeric (e.g. "contact[0][name]",
136
+ * "contact[1][name]") into arrays of objects. Objects with any non-numeric key are
137
+ * left as-is.
138
+ */
139
+ const arrayify = (value: any): any => {
140
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
141
+ return value;
142
+ }
143
+
144
+ const keys = Object.keys(value);
145
+ const allNumeric = keys.length > 0 && keys.every((key) => /^\d+$/.test(key));
146
+
147
+ if (allNumeric) {
148
+ const array: any[] = [];
149
+ for (const key of keys.sort((a, b) => Number(a) - Number(b))) {
150
+ array[Number(key)] = arrayify(value[key]);
151
+ }
152
+ return array;
153
+ }
154
+
155
+ for (const key of keys) {
156
+ value[key] = arrayify(value[key]);
157
+ }
158
+ return value;
159
+ };
160
+
134
161
  for (const pair of formData.entries()) {
135
162
  assign(parseKey(pair[0]), pair[1], object);
136
163
  }
137
164
 
138
- return object;
165
+ return arrayify(object);
139
166
  }
140
167
 
141
168
  /**