@coherent.js/client 1.0.0-beta.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Thomas Drouvin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # @coherent.js/client
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@coherent.js/client.svg)](https://www.npmjs.com/package/@coherent.js/client)
4
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](../../LICENSE)
5
+ [![Node >= 20](https://img.shields.io/badge/node-%3E%3D20-brightgreen)](https://nodejs.org)
6
+
7
+ Client-side hydration and HMR utilities for Coherent.js applications.
8
+
9
+ - ESM-only, Node 20+
10
+ - Progressive enhancement for server-rendered HTML
11
+ - Lightweight event system and instance lifecycle helpers
12
+ - Optional HMR support for dev workflows
13
+
14
+ For a high-level overview and repository-wide instructions, see the root README: ../../README.md
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pnpm add @coherent.js/client
20
+ ```
21
+
22
+ Requirements:
23
+ - Node.js >= 20
24
+ - ESM module system
25
+
26
+ ## Quick start
27
+
28
+ The client package pairs with server-rendered HTML produced by `@coherent.js/core`.
29
+
30
+ JavaScript (ESM):
31
+ ```js
32
+ import { autoHydrate } from '@coherent.js/client';
33
+
34
+ // Hydrate elements that were marked as hydratable on the server
35
+ autoHydrate();
36
+ ```
37
+
38
+ TypeScript:
39
+ ```ts
40
+ import { autoHydrate } from '@coherent.js/client';
41
+
42
+ document.addEventListener('DOMContentLoaded', () => {
43
+ autoHydrate();
44
+ });
45
+ ```
46
+
47
+ ### Attaching custom handlers
48
+
49
+ The client exposes an event registry you can populate during hydration.
50
+
51
+ ```js
52
+ import { registerEventHandler } from '@coherent.js/client';
53
+
54
+ registerEventHandler('increment', (el, evt, ctx) => {
55
+ // custom logic using element, DOM event, and context
56
+ });
57
+ ```
58
+
59
+ TypeScript:
60
+ ```ts
61
+ import { registerEventHandler } from '@coherent.js/client';
62
+
63
+ type Ctx = { state?: unknown };
64
+
65
+ registerEventHandler('increment', (el: HTMLElement, evt: Event, ctx: Ctx) => {
66
+ console.log('clicked', el, ctx);
67
+ });
68
+ ```
69
+
70
+ ## Notes on testing
71
+
72
+ When testing client-side utilities in Node, provide light DOM shims (see repository tests under `packages/client/test/`). Example:
73
+
74
+ ```js
75
+ import { vi } from 'vitest';
76
+
77
+ global.window = { __coherentEventRegistry: {}, addEventListener: vi.fn() };
78
+ global.document = { querySelector: vi.fn(), querySelectorAll: vi.fn(() => []) };
79
+ ```
80
+
81
+ ## Development
82
+
83
+ Run tests for this package:
84
+ ```bash
85
+ pnpm --filter @coherent.js/client run test
86
+ ```
87
+
88
+ Watch mode:
89
+ ```bash
90
+ pnpm --filter @coherent.js/client run test:watch
91
+ ```
92
+
93
+ Type check:
94
+ ```bash
95
+ pnpm --filter @coherent.js/client run typecheck
96
+ ```
97
+
98
+ Build:
99
+ ```bash
100
+ pnpm --filter @coherent.js/client run build
101
+ ```
102
+
103
+ ## License
104
+
105
+ MIT © Coherent.js Team
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=hmr.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hmr.d.ts","sourceRoot":"","sources":["../../../../src/client/hmr.js"],"names":[],"mappings":""}
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ /*
3
+ * Coherent.js HMR Client
4
+ * Auto-connects to the dev server and applies updates.
5
+ */
6
+ (function initHMR() {
7
+ if (typeof window === 'undefined')
8
+ return;
9
+ if (window.__coherent_hmr_initialized)
10
+ return;
11
+ window.__coherent_hmr_initialized = true;
12
+ const log = (...args) => console.log('[Coherent HMR]', ...args);
13
+ const warn = (...args) => console.warn('[Coherent HMR]', ...args);
14
+ const _error = (...args) => console.error('[Coherent HMR]', ...args);
15
+ let hadDisconnect = false;
16
+ function connect() {
17
+ try {
18
+ const protocol = location.protocol === 'https:' ? 'wss' : 'ws';
19
+ const wsUrl = `${protocol}://${location.host}`;
20
+ const ws = new WebSocket(wsUrl);
21
+ ws.addEventListener('open', () => {
22
+ log('connected');
23
+ ws.send(JSON.stringify({ type: 'connected' }));
24
+ // If the server was restarted, ensure the page HTML is refreshed automatically
25
+ if (hadDisconnect) {
26
+ log('reconnected, reloading page');
27
+ setTimeout(() => location.reload(), 200);
28
+ return;
29
+ }
30
+ });
31
+ ws.addEventListener('close', () => {
32
+ hadDisconnect = true;
33
+ warn('disconnected, retrying in 1s...');
34
+ setTimeout(connect, 1000);
35
+ });
36
+ ws.addEventListener('error', (e) => {
37
+ error('socket error', e);
38
+ try {
39
+ ws.close();
40
+ }
41
+ catch { }
42
+ });
43
+ ws.addEventListener('message', async (evt) => {
44
+ let data;
45
+ try {
46
+ data = JSON.parse(evt.data);
47
+ }
48
+ catch {
49
+ return;
50
+ }
51
+ log('message', data.type, data.filePath || data.webPath || '');
52
+ switch (data.type) {
53
+ case 'connected':
54
+ break;
55
+ case 'hmr-full-reload':
56
+ case 'reload':
57
+ warn('server requested full reload');
58
+ location.reload();
59
+ return;
60
+ case 'preview-update':
61
+ // No-op here; dashboard uses this for live preview panes
62
+ break;
63
+ case 'hmr-component-update':
64
+ case 'hmr-update':
65
+ await handleUpdate(data);
66
+ break;
67
+ default:
68
+ break;
69
+ }
70
+ });
71
+ }
72
+ catch {
73
+ // Ignore errors in non-browser environments
74
+ }
75
+ }
76
+ async function handleUpdate(msg) {
77
+ const filePath = msg.webPath || msg.filePath || '';
78
+ const ts = Date.now();
79
+ // Try to re-import changed module to refresh side effects/registrations
80
+ try {
81
+ // Prefer absolute path from dev-server, otherwise attempt as-is
82
+ const importPath = filePath.startsWith('/') ? filePath : `/${filePath}`;
83
+ await import(`${importPath}?t=${ts}`);
84
+ log('updated', msg.updateType || 'module', filePath);
85
+ }
86
+ catch (err) {
87
+ warn('module re-import failed, attempting soft hydrate', filePath, err);
88
+ }
89
+ // Attempt to re-hydrate if available
90
+ try {
91
+ const { autoHydrate } = await import('/src/client/hydration.js');
92
+ // If examples register a component registry on window, prefer targeted hydrate
93
+ if (window.componentRegistry) {
94
+ autoHydrate(window.componentRegistry);
95
+ }
96
+ else {
97
+ autoHydrate();
98
+ }
99
+ }
100
+ catch {
101
+ warn('autoHydrate failed; falling back to full reload');
102
+ location.reload();
103
+ }
104
+ }
105
+ connect();
106
+ })();
107
+ //# sourceMappingURL=hmr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hmr.js","sourceRoot":"","sources":["../../../../src/client/hmr.js"],"names":[],"mappings":";AAAA;;;GAGG;AAEH,CAAC,SAAS,OAAO;IACf,IAAI,OAAO,MAAM,KAAK,WAAW;QAAE,OAAO;IAC1C,IAAI,MAAM,CAAC,0BAA0B;QAAE,OAAO;IAC9C,MAAM,CAAC,0BAA0B,GAAG,IAAI,CAAC;IAEzC,MAAM,GAAG,GAAG,C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AO,IAAI,GAAG,CAAC,QAAQ,IAAI,EAAE,CAAC;QACnD,MAAM,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAEtB,wEAAwE;QACxE,IAAI,CAAC;YACH,gEAAgE;YAChE,MAAM,UAAU,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,QAAQ,EAAE,CAAC;YACxE,MAAM,MAAM,CAAC,GAAG,UAAU,MAAM,EAAE,EAAE,CAAC,CAAC;YACtC,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,UAAU,IAAI,QAAQ,EAAE,QAAQ,CAAC,CAAC;QACvD,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,kDAAkD,EAAE,QAAQ,EAAE,GAAG,CAAC,CAAC;QAC1E,CAAC;QAED,qCAAqC;QACrC,IAAI,CAAC;YACH,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,MAAM,CAAC,0BAA0B,CAAC,CAAC;YACjE,+EAA+E;YAC/E,IAAI,MAAM,CAAC,iBAAiB,EAAE,CAAC;gBAC7B,WAAW,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;YACxC,CAAC;iBAAM,CAAC;gBACN,WAAW,EAAE,CAAC;YAChB,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,CAAC,iDAAiD,CAAC,CAAC;YACxD,QAAQ,CAAC,MAAM,EAAE,CAAC;QACpB,CAAC;IACH,CAAC;IAED,OAAO,EAAE,CAAC;AACZ,CAAC,CAAC,EAAE,CAAC"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Register an event handler for later use
3
+ * @param {string} id - Unique identifier for the event handler
4
+ * @param {Function} handler - The event handler function
5
+ */
6
+ export function registerEventHandler(id: string, handler: Function): void;
7
+ /**
8
+ * Hydrate a DOM element with a Coherent component
9
+ *
10
+ * @param {HTMLElement} element - The DOM element to hydrate
11
+ * @param {Function} component - The Coherent component function
12
+ * @param {Object} props - The props to pass to the component
13
+ * @param {Object} options - Hydration options
14
+ * @returns {Object} The hydrated component instance
15
+ */
16
+ export function hydrate(element: HTMLElement, component: Function, props?: Object, options?: Object): Object;
17
+ /**
18
+ * Hydrate multiple elements with their corresponding components
19
+ *
20
+ * @param {Array} elements - Array of DOM elements to hydrate
21
+ * @param {Array} components - Array of Coherent component functions
22
+ * @param {Array} propsArray - Array of props for each component
23
+ * @returns {Array} Array of hydrated component instances
24
+ */
25
+ export function hydrateAll(elements: any[], components: any[], propsArray?: any[]): any[];
26
+ /**
27
+ * Find and hydrate elements by CSS selector
28
+ *
29
+ * @param {string} selector - CSS selector to find elements
30
+ * @param {Function} component - The Coherent component function
31
+ * @param {Object} props - The props to pass to the component
32
+ * @returns {Array} Array of hydrated component instances
33
+ */
34
+ export function hydrateBySelector(selector: string, component: Function, props?: Object): any[];
35
+ /**
36
+ * Enable client-side interactivity for event handlers
37
+ *
38
+ * @param {HTMLElement} rootElement - The root element to enable events on
39
+ */
40
+ export function enableClientEvents(rootElement?: HTMLElement): void;
41
+ /**
42
+ * Create a hydratable component
43
+ *
44
+ * @param {Function} component - The Coherent component function
45
+ * @param {Object} options - Hydration options
46
+ * @returns {Function} A component that can be hydrated
47
+ */
48
+ export function makeHydratable(component: Function, options?: Object): Function;
49
+ /**
50
+ * Auto-hydrate all components on page load
51
+ *
52
+ * @param {Object} componentRegistry - Registry of component functions
53
+ */
54
+ export function autoHydrate(componentRegistry?: Object): void;
55
+ //# sourceMappingURL=hydration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration.d.ts","sourceRoot":"","sources":["../../../../src/client/hydration.js"],"names":[],"mappings":"AAomBA;;;;GAIG;AACH,yCAHW,MAAM,2BAKhB;AA/hBD;;;;;;;;GAQG;AACH,iCANW,WAAW,+BAEX,MAAM,YACN,MAAM,GACJ,MAAM,CA4gBlB;AA44BD;;;;;;;GAOG;AACH,0FAUC;AAED;;;;;;;GAOG;AACH,4CALW,MAAM,+BAEN,MAAM,SAUhB;AAED;;;;GAIG;AACH,iDAFW,WAAW,QAUrB;AAED;;;;;;GAMG;AACH,8DAHW,MAAM,YAsIhB;AAED;;;;GAIG;AACH,gDAFW,MAAM,QAgFhB"}