@mandujs/core 0.19.0 → 0.19.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.
Files changed (90) hide show
  1. package/README.ko.md +0 -14
  2. package/package.json +4 -1
  3. package/src/brain/architecture/analyzer.ts +4 -4
  4. package/src/brain/doctor/analyzer.ts +18 -14
  5. package/src/bundler/build.test.ts +127 -0
  6. package/src/bundler/build.ts +291 -113
  7. package/src/bundler/css.ts +20 -5
  8. package/src/bundler/dev.ts +55 -2
  9. package/src/bundler/prerender.ts +195 -0
  10. package/src/change/snapshot.ts +4 -23
  11. package/src/change/types.ts +2 -3
  12. package/src/client/Form.tsx +105 -0
  13. package/src/client/__tests__/use-sse.test.ts +153 -0
  14. package/src/client/hooks.ts +105 -6
  15. package/src/client/index.ts +35 -6
  16. package/src/client/router.ts +670 -433
  17. package/src/client/rpc.ts +140 -0
  18. package/src/client/runtime.ts +24 -21
  19. package/src/client/use-fetch.ts +239 -0
  20. package/src/client/use-head.ts +197 -0
  21. package/src/client/use-sse.ts +378 -0
  22. package/src/components/Image.tsx +162 -0
  23. package/src/config/mandu.ts +5 -0
  24. package/src/config/validate.ts +34 -0
  25. package/src/content/index.ts +5 -1
  26. package/src/devtools/client/catchers/error-catcher.ts +17 -0
  27. package/src/devtools/client/catchers/network-proxy.ts +390 -367
  28. package/src/devtools/client/components/kitchen-root.tsx +479 -467
  29. package/src/devtools/client/components/panel/diff-viewer.tsx +219 -0
  30. package/src/devtools/client/components/panel/guard-panel.tsx +374 -244
  31. package/src/devtools/client/components/panel/index.ts +45 -32
  32. package/src/devtools/client/components/panel/panel-container.tsx +332 -312
  33. package/src/devtools/client/components/panel/preview-panel.tsx +188 -0
  34. package/src/devtools/client/state-manager.ts +535 -478
  35. package/src/devtools/design-tokens.ts +265 -264
  36. package/src/devtools/types.ts +345 -319
  37. package/src/filling/filling.ts +336 -14
  38. package/src/filling/index.ts +5 -1
  39. package/src/filling/session.ts +216 -0
  40. package/src/filling/ws.ts +78 -0
  41. package/src/generator/generate.ts +2 -2
  42. package/src/guard/auto-correct.ts +0 -29
  43. package/src/guard/check.ts +14 -31
  44. package/src/guard/presets/index.ts +296 -294
  45. package/src/guard/rules.ts +15 -19
  46. package/src/guard/validator.ts +834 -834
  47. package/src/index.ts +5 -1
  48. package/src/island/index.ts +373 -304
  49. package/src/kitchen/api/contract-api.ts +225 -0
  50. package/src/kitchen/api/diff-parser.ts +108 -0
  51. package/src/kitchen/api/file-api.ts +273 -0
  52. package/src/kitchen/api/guard-api.ts +83 -0
  53. package/src/kitchen/api/guard-decisions.ts +100 -0
  54. package/src/kitchen/api/routes-api.ts +50 -0
  55. package/src/kitchen/index.ts +21 -0
  56. package/src/kitchen/kitchen-handler.ts +256 -0
  57. package/src/kitchen/kitchen-ui.ts +1732 -0
  58. package/src/kitchen/stream/activity-sse.ts +145 -0
  59. package/src/kitchen/stream/file-tailer.ts +99 -0
  60. package/src/middleware/compress.ts +62 -0
  61. package/src/middleware/cors.ts +47 -0
  62. package/src/middleware/index.ts +10 -0
  63. package/src/middleware/jwt.ts +134 -0
  64. package/src/middleware/logger.ts +58 -0
  65. package/src/middleware/timeout.ts +55 -0
  66. package/src/paths.ts +0 -4
  67. package/src/plugins/hooks.ts +64 -0
  68. package/src/plugins/index.ts +3 -0
  69. package/src/plugins/types.ts +5 -0
  70. package/src/report/build.ts +0 -6
  71. package/src/resource/__tests__/backward-compat.test.ts +0 -1
  72. package/src/router/fs-patterns.ts +11 -1
  73. package/src/router/fs-routes.ts +78 -14
  74. package/src/router/fs-scanner.ts +2 -2
  75. package/src/router/fs-types.ts +2 -1
  76. package/src/runtime/adapter-bun.ts +62 -0
  77. package/src/runtime/adapter.ts +47 -0
  78. package/src/runtime/cache.ts +310 -0
  79. package/src/runtime/handler.ts +65 -0
  80. package/src/runtime/image-handler.ts +195 -0
  81. package/src/runtime/index.ts +12 -0
  82. package/src/runtime/middleware.ts +263 -0
  83. package/src/runtime/server.ts +662 -83
  84. package/src/runtime/ssr.ts +55 -29
  85. package/src/runtime/streaming-ssr.ts +106 -82
  86. package/src/spec/index.ts +0 -1
  87. package/src/spec/schema.ts +1 -0
  88. package/src/testing/index.ts +144 -0
  89. package/src/watcher/watcher.ts +27 -1
  90. package/src/spec/lock.ts +0 -56
@@ -1,304 +1,373 @@
1
- /**
2
- * Mandu Island - 선언적 Islands Architecture
3
- *
4
- * @example
5
- * ```tsx
6
- * import { island } from '@mandujs/core';
7
- *
8
- * export default island('visible', ({ name }) => {
9
- * const [count, setCount] = useState(0);
10
- * return <button onClick={() => setCount(c => c + 1)}>{name}: {count}</button>;
11
- * });
12
- * ```
13
- */
14
-
15
- import type { ComponentType, ReactNode } from 'react';
16
- import { z } from 'zod';
17
-
18
- // ============================================================================
19
- // Types
20
- // ============================================================================
21
-
22
- /** 하이드레이션 타이밍 */
23
- export type IslandHydrationStrategy =
24
- | 'load' // 페이지 로드 즉시
25
- | 'idle' // requestIdleCallback
26
- | 'visible' // IntersectionObserver
27
- | 'media' // 미디어 쿼리 매치 시
28
- | 'never'; // SSR only, 하이드레이션 안 함
29
-
30
- /** Island 옵션 */
31
- export interface IslandOptions<P = unknown> {
32
- /** 하이드레이션 전략 */
33
- hydrate: IslandHydrationStrategy;
34
- /** 미디어 쿼리 (hydrate: 'media' 일 때) */
35
- media?: string;
36
- /** SSR 폴백 컴포넌트 */
37
- fallback?: ReactNode;
38
- /** Props 스키마 (Zod) - 런타임 검증 */
39
- props?: z.ZodType<P>;
40
- /** Island 이름 (자동 생성됨) */
41
- name?: string;
42
- }
43
-
44
- /** Island 컴포넌트 메타데이터 */
45
- export interface IslandMeta {
46
- __island: true;
47
- __hydrate: IslandHydrationStrategy;
48
- __media?: string;
49
- __fallback?: ReactNode;
50
- __name: string;
51
- __propsSchema?: z.ZodType<unknown>;
52
- }
53
-
54
- /** Island 컴포넌트 타입 */
55
- export type IslandComponent<P = unknown> = ComponentType<P> & IslandMeta;
56
-
57
- // ============================================================================
58
- // Island Registry (서버/클라이언트 공용)
59
- // ============================================================================
60
-
61
- const islandRegistry = new Map<string, IslandComponent<any>>();
62
- let islandCounter = 0;
63
-
64
- export function registerIsland(name: string, component: IslandComponent<any>): void {
65
- islandRegistry.set(name, component);
66
- }
67
-
68
- export function getIsland(name: string): IslandComponent<any> | undefined {
69
- return islandRegistry.get(name);
70
- }
71
-
72
- export function getAllIslands(): Map<string, IslandComponent<any>> {
73
- return islandRegistry;
74
- }
75
-
76
- // ============================================================================
77
- // island() - 선언적 Island 생성
78
- // ============================================================================
79
-
80
- /**
81
- * 선언적 Island 컴포넌트 생성
82
- *
83
- * @example
84
- * // 간단한 사용
85
- * export default island('visible', ({ name }) => <div>{name}</div>);
86
- *
87
- * @example
88
- * // 옵션과 함께
89
- * export default island({
90
- * hydrate: 'idle',
91
- * fallback: <Skeleton />,
92
- * props: z.object({ userId: z.string() }),
93
- * }, ({ userId }) => {
94
- * // ...
95
- * });
96
- */
97
- export function island<P extends Record<string, unknown>>(
98
- strategy: IslandHydrationStrategy,
99
- Component: ComponentType<P>
100
- ): IslandComponent<P>;
101
-
102
- export function island<P extends Record<string, unknown>>(
103
- options: IslandOptions<P>,
104
- Component: ComponentType<P>
105
- ): IslandComponent<P>;
106
-
107
- export function island<P extends Record<string, unknown>>(
108
- strategyOrOptions: IslandHydrationStrategy | IslandOptions<P>,
109
- Component: ComponentType<P>
110
- ): IslandComponent<P> {
111
- const options: IslandOptions<P> = typeof strategyOrOptions === 'string'
112
- ? { hydrate: strategyOrOptions }
113
- : strategyOrOptions;
114
-
115
- const name = options.name || `island_${++islandCounter}_${Component.name || 'Anonymous'}`;
116
-
117
- // Island 메타데이터 부착
118
- const IslandWrapper = Component as IslandComponent<P>;
119
- IslandWrapper.__island = true;
120
- IslandWrapper.__hydrate = options.hydrate;
121
- IslandWrapper.__media = options.media;
122
- IslandWrapper.__fallback = options.fallback;
123
- IslandWrapper.__name = name;
124
- IslandWrapper.__propsSchema = options.props;
125
-
126
- // 레지스트리에 등록
127
- registerIsland(name, IslandWrapper);
128
-
129
- return IslandWrapper;
130
- }
131
-
132
- // ============================================================================
133
- // isIsland() - Island 컴포넌트 체크
134
- // ============================================================================
135
-
136
- export function isIsland(component: unknown): component is IslandComponent<any> {
137
- return (
138
- typeof component === 'function' &&
139
- (component as IslandComponent<any>).__island === true
140
- );
141
- }
142
-
143
- // ============================================================================
144
- // serializeIslandProps() - Props 직렬화
145
- // ============================================================================
146
-
147
- export function serializeIslandProps(props: Record<string, unknown>): string {
148
- return JSON.stringify(props, (_, value) => {
149
- // Date 처리
150
- if (value instanceof Date) {
151
- return { __type: 'Date', value: value.toISOString() };
152
- }
153
- // Map 처리
154
- if (value instanceof Map) {
155
- return { __type: 'Map', value: Array.from(value.entries()) };
156
- }
157
- // Set 처리
158
- if (value instanceof Set) {
159
- return { __type: 'Set', value: Array.from(value) };
160
- }
161
- // 함수는 직렬화 불가
162
- if (typeof value === 'function') {
163
- console.warn('[Mandu Island] Functions cannot be serialized as props');
164
- return undefined;
165
- }
166
- return value;
167
- });
168
- }
169
-
170
- // ============================================================================
171
- // deserializeIslandProps() - Props 역직렬화
172
- // ============================================================================
173
-
174
- export function deserializeIslandProps(json: string): Record<string, unknown> {
175
- return JSON.parse(json, (_, value) => {
176
- if (value && typeof value === 'object' && '__type' in value) {
177
- switch (value.__type) {
178
- case 'Date':
179
- return new Date(value.value);
180
- case 'Map':
181
- return new Map(value.value);
182
- case 'Set':
183
- return new Set(value.value);
184
- }
185
- }
186
- return value;
187
- });
188
- }
189
-
190
- // ============================================================================
191
- // createIslandPlaceholder() - SSR용 플레이스홀더 생성
192
- // ============================================================================
193
-
194
- export interface IslandPlaceholderProps {
195
- name: string;
196
- props: Record<string, unknown>;
197
- hydrate: IslandHydrationStrategy;
198
- media?: string;
199
- fallback?: ReactNode;
200
- }
201
-
202
- export function createIslandPlaceholder({
203
- name,
204
- props,
205
- hydrate,
206
- media,
207
- fallback,
208
- }: IslandPlaceholderProps): string {
209
- const serializedProps = serializeIslandProps(props);
210
- const fallbackHtml = fallback ? renderFallback(fallback) : '<div class="mandu-island-loading">Loading...</div>';
211
-
212
- return `<div data-mandu-island="${name}" data-hydrate="${hydrate}"${media ? ` data-media="${media}"` : ''} data-props='${escapeHtml(serializedProps)}'>${fallbackHtml}</div>`;
213
- }
214
-
215
- function escapeHtml(str: string): string {
216
- return str
217
- .replace(/&/g, '&amp;')
218
- .replace(/'/g, '&#39;')
219
- .replace(/"/g, '&quot;')
220
- .replace(/</g, '&lt;')
221
- .replace(/>/g, '&gt;');
222
- }
223
-
224
- function renderFallback(fallback: ReactNode): string {
225
- // 간단한 fallback 처리 (실제로는 react-dom/server 사용)
226
- if (typeof fallback === 'string') return fallback;
227
- if (fallback === null || fallback === undefined) return '';
228
- return '<div class="mandu-island-loading">Loading...</div>';
229
- }
230
-
231
- // ============================================================================
232
- // Client Hydration Script
233
- // ============================================================================
234
-
235
- export const ISLAND_HYDRATION_SCRIPT = `
236
- <script type="module">
237
- (function() {
238
- const strategies = {
239
- load: (el, hydrate) => hydrate(),
240
- idle: (el, hydrate) => {
241
- if ('requestIdleCallback' in window) {
242
- requestIdleCallback(hydrate);
243
- } else {
244
- setTimeout(hydrate, 200);
245
- }
246
- },
247
- visible: (el, hydrate) => {
248
- const observer = new IntersectionObserver((entries) => {
249
- if (entries[0].isIntersecting) {
250
- observer.disconnect();
251
- hydrate();
252
- }
253
- });
254
- observer.observe(el);
255
- },
256
- media: (el, hydrate, query) => {
257
- const mql = window.matchMedia(query);
258
- if (mql.matches) {
259
- hydrate();
260
- } else {
261
- mql.addEventListener('change', (e) => {
262
- if (e.matches) hydrate();
263
- }, { once: true });
264
- }
265
- },
266
- never: () => {},
267
- };
268
-
269
- window.__MANDU_HYDRATE_ISLAND__ = async function(el, Component) {
270
- const strategy = el.dataset.hydrate || 'load';
271
- const media = el.dataset.media;
272
- const props = JSON.parse(el.dataset.props || '{}');
273
-
274
- const doHydrate = async () => {
275
- const { createRoot } = await import('react-dom/client');
276
- const root = createRoot(el);
277
- root.render(window.React.createElement(Component, props));
278
- el.dataset.hydrated = 'true';
279
- console.log('[Mandu] Island hydrated:', el.dataset.manduIsland);
280
- };
281
-
282
- if (strategy === 'media' && media) {
283
- strategies.media(el, doHydrate, media);
284
- } else {
285
- strategies[strategy]?.(el, doHydrate);
286
- }
287
- };
288
-
289
- // Auto-discover and hydrate islands
290
- document.querySelectorAll('[data-mandu-island]').forEach(el => {
291
- const name = el.dataset.manduIsland;
292
- if (window.__MANDU_ISLANDS__?.[name]) {
293
- window.__MANDU_HYDRATE_ISLAND__(el, window.__MANDU_ISLANDS__[name]);
294
- }
295
- });
296
- })();
297
- </script>
298
- `;
299
-
300
- // ============================================================================
301
- // Exports
302
- // ============================================================================
303
-
304
- export type { ComponentType, ReactNode };
1
+ /**
2
+ * Mandu Island - 선언적 Islands Architecture
3
+ *
4
+ * @example
5
+ * ```tsx
6
+ * import { island } from '@mandujs/core';
7
+ *
8
+ * export default island('visible', ({ name }) => {
9
+ * const [count, setCount] = useState(0);
10
+ * return <button onClick={() => setCount(c => c + 1)}>{name}: {count}</button>;
11
+ * });
12
+ * ```
13
+ */
14
+
15
+ import type { ComponentType, ReactNode } from 'react';
16
+ import { z } from 'zod';
17
+
18
+ // ============================================================================
19
+ // Types
20
+ // ============================================================================
21
+
22
+ /** 하이드레이션 타이밍 */
23
+ export type IslandHydrationStrategy =
24
+ | 'load' // 페이지 로드 즉시
25
+ | 'idle' // requestIdleCallback
26
+ | 'visible' // IntersectionObserver
27
+ | 'media' // 미디어 쿼리 매치 시
28
+ | 'never'; // SSR only, 하이드레이션 안 함
29
+
30
+ /** Island 옵션 */
31
+ export interface IslandOptions<P = unknown> {
32
+ /** 하이드레이션 전략 */
33
+ hydrate: IslandHydrationStrategy;
34
+ /** 미디어 쿼리 (hydrate: 'media' 일 때) */
35
+ media?: string;
36
+ /** SSR 폴백 컴포넌트 */
37
+ fallback?: ReactNode;
38
+ /** Props 스키마 (Zod) - 런타임 검증 */
39
+ props?: z.ZodType<P>;
40
+ /** Island 이름 (자동 생성됨) */
41
+ name?: string;
42
+ }
43
+
44
+ /** Island 컴포넌트 메타데이터 */
45
+ export interface IslandMeta {
46
+ __island: true;
47
+ __hydrate: IslandHydrationStrategy;
48
+ __media?: string;
49
+ __fallback?: ReactNode;
50
+ __name: string;
51
+ __propsSchema?: z.ZodType<unknown>;
52
+ }
53
+
54
+ /** Island 컴포넌트 타입 */
55
+ export type IslandComponent<P = unknown> = ComponentType<P> & IslandMeta;
56
+
57
+ // ============================================================================
58
+ // Island Registry (서버/클라이언트 공용)
59
+ // ============================================================================
60
+
61
+ const islandRegistry = new Map<string, IslandComponent<any>>();
62
+ let islandCounter = 0;
63
+
64
+ export function registerIsland(name: string, component: IslandComponent<any>): void {
65
+ islandRegistry.set(name, component);
66
+ }
67
+
68
+ export function getIsland(name: string): IslandComponent<any> | undefined {
69
+ return islandRegistry.get(name);
70
+ }
71
+
72
+ export function getAllIslands(): Map<string, IslandComponent<any>> {
73
+ return islandRegistry;
74
+ }
75
+
76
+ // ============================================================================
77
+ // Client Island Types (setup/render 패턴)
78
+ // ============================================================================
79
+
80
+ /**
81
+ * Client Island 정의 타입 (setup/render 패턴)
82
+ * @template TServerData - SSR에서 전달받는 서버 데이터 타입
83
+ * @template TSetupResult - setup 함수가 반환하는 결과 타입
84
+ */
85
+ export interface ClientIslandDefinition<TServerData, TSetupResult> {
86
+ setup: (serverData: TServerData) => TSetupResult;
87
+ render: (props: TSetupResult) => ReactNode;
88
+ errorBoundary?: (error: Error, reset: () => void) => ReactNode;
89
+ loading?: () => ReactNode;
90
+ }
91
+
92
+ /** Compiled Client Island */
93
+ export interface CompiledClientIsland<TServerData, TSetupResult> {
94
+ definition: ClientIslandDefinition<TServerData, TSetupResult>;
95
+ __mandu_island: true;
96
+ __mandu_island_id?: string;
97
+ }
98
+
99
+ /** Type guard: is this a ClientIslandDefinition? */
100
+ function isClientIslandDefinition(arg: unknown): arg is ClientIslandDefinition<unknown, unknown> {
101
+ return (
102
+ arg !== null &&
103
+ typeof arg === 'object' &&
104
+ 'setup' in arg &&
105
+ 'render' in arg &&
106
+ typeof (arg as any).setup === 'function' &&
107
+ typeof (arg as any).render === 'function'
108
+ );
109
+ }
110
+
111
+ // ============================================================================
112
+ // island() - 선언적 Island 생성 + Client Island 패턴
113
+ // ============================================================================
114
+
115
+ /**
116
+ * Island 컴포넌트 생성 (두 가지 패턴 지원)
117
+ *
118
+ * @example
119
+ * // 패턴 1: 선언적 (컴포넌트 래핑)
120
+ * export default island('visible', ({ name }) => <div>{name}</div>);
121
+ *
122
+ * @example
123
+ * // 패턴 2: Setup/Render (클라이언트 하이드레이션)
124
+ * export default island<TodosData>({
125
+ * setup: (serverData) => {
126
+ * const [todos, setTodos] = useState(serverData.todos);
127
+ * return { todos, setTodos };
128
+ * },
129
+ * render: ({ todos }) => <ul>{todos.map(t => <li key={t.id}>{t.title}</li>)}</ul>,
130
+ * });
131
+ *
132
+ * @example
133
+ * // 패턴 1: 옵션과 함께
134
+ * export default island({
135
+ * hydrate: 'idle',
136
+ * fallback: <Skeleton />,
137
+ * props: z.object({ userId: z.string() }),
138
+ * }, ({ userId }) => {
139
+ * // ...
140
+ * });
141
+ */
142
+
143
+ // Overload 1: Setup/Render client island pattern
144
+ export function island<TServerData, TSetupResult = TServerData>(
145
+ definition: ClientIslandDefinition<TServerData, TSetupResult>
146
+ ): CompiledClientIsland<TServerData, TSetupResult>;
147
+
148
+ // Overload 2: Declarative with strategy string
149
+ export function island<P extends Record<string, unknown>>(
150
+ strategy: IslandHydrationStrategy,
151
+ Component: ComponentType<P>
152
+ ): IslandComponent<P>;
153
+
154
+ // Overload 3: Declarative with options
155
+ export function island<P extends Record<string, unknown>>(
156
+ options: IslandOptions<P>,
157
+ Component: ComponentType<P>
158
+ ): IslandComponent<P>;
159
+
160
+ // Implementation
161
+ export function island(
162
+ strategyOrOptionsOrDefinition: IslandHydrationStrategy | IslandOptions<any> | ClientIslandDefinition<any, any>,
163
+ Component?: ComponentType<any>
164
+ ): IslandComponent<any> | CompiledClientIsland<any, any> {
165
+ // Pattern 2: Setup/Render client island
166
+ if (Component === undefined && isClientIslandDefinition(strategyOrOptionsOrDefinition)) {
167
+ return {
168
+ definition: strategyOrOptionsOrDefinition,
169
+ __mandu_island: true,
170
+ };
171
+ }
172
+
173
+ // Pattern 1: Declarative island wrapping
174
+ if (!Component) {
175
+ throw new Error('[Mandu Island] Component is required for declarative island pattern');
176
+ }
177
+
178
+ const options: IslandOptions<any> = typeof strategyOrOptionsOrDefinition === 'string'
179
+ ? { hydrate: strategyOrOptionsOrDefinition }
180
+ : strategyOrOptionsOrDefinition as IslandOptions<any>;
181
+
182
+ const name = options.name || `island_${++islandCounter}_${Component.name || 'Anonymous'}`;
183
+
184
+ // Island 메타데이터 부착
185
+ const IslandWrapper = Component as IslandComponent<any>;
186
+ IslandWrapper.__island = true;
187
+ IslandWrapper.__hydrate = options.hydrate;
188
+ IslandWrapper.__media = options.media;
189
+ IslandWrapper.__fallback = options.fallback;
190
+ IslandWrapper.__name = name;
191
+ IslandWrapper.__propsSchema = options.props;
192
+
193
+ // 레지스트리에 등록
194
+ registerIsland(name, IslandWrapper);
195
+
196
+ return IslandWrapper;
197
+ }
198
+
199
+ // ============================================================================
200
+ // isIsland() - Island 컴포넌트 체크
201
+ // ============================================================================
202
+
203
+ export function isIsland(component: unknown): component is IslandComponent<any> {
204
+ return (
205
+ typeof component === 'function' &&
206
+ (component as IslandComponent<any>).__island === true
207
+ );
208
+ }
209
+
210
+ // ============================================================================
211
+ // serializeIslandProps() - Props 직렬화
212
+ // ============================================================================
213
+
214
+ export function serializeIslandProps(props: Record<string, unknown>): string {
215
+ return JSON.stringify(props, (_, value) => {
216
+ // Date 처리
217
+ if (value instanceof Date) {
218
+ return { __type: 'Date', value: value.toISOString() };
219
+ }
220
+ // Map 처리
221
+ if (value instanceof Map) {
222
+ return { __type: 'Map', value: Array.from(value.entries()) };
223
+ }
224
+ // Set 처리
225
+ if (value instanceof Set) {
226
+ return { __type: 'Set', value: Array.from(value) };
227
+ }
228
+ // 함수는 직렬화 불가
229
+ if (typeof value === 'function') {
230
+ console.warn('[Mandu Island] Functions cannot be serialized as props');
231
+ return undefined;
232
+ }
233
+ return value;
234
+ });
235
+ }
236
+
237
+ // ============================================================================
238
+ // deserializeIslandProps() - Props 역직렬화
239
+ // ============================================================================
240
+
241
+ export function deserializeIslandProps(json: string): Record<string, unknown> {
242
+ return JSON.parse(json, (_, value) => {
243
+ if (value && typeof value === 'object' && '__type' in value) {
244
+ switch (value.__type) {
245
+ case 'Date':
246
+ return new Date(value.value);
247
+ case 'Map':
248
+ return new Map(value.value);
249
+ case 'Set':
250
+ return new Set(value.value);
251
+ }
252
+ }
253
+ return value;
254
+ });
255
+ }
256
+
257
+ // ============================================================================
258
+ // createIslandPlaceholder() - SSR용 플레이스홀더 생성
259
+ // ============================================================================
260
+
261
+ export interface IslandPlaceholderProps {
262
+ name: string;
263
+ props: Record<string, unknown>;
264
+ hydrate: IslandHydrationStrategy;
265
+ media?: string;
266
+ fallback?: ReactNode;
267
+ }
268
+
269
+ export function createIslandPlaceholder({
270
+ name,
271
+ props,
272
+ hydrate,
273
+ media,
274
+ fallback,
275
+ }: IslandPlaceholderProps): string {
276
+ const serializedProps = serializeIslandProps(props);
277
+ const fallbackHtml = fallback ? renderFallback(fallback) : '<div class="mandu-island-loading">Loading...</div>';
278
+
279
+ return `<div data-mandu-island="${name}" data-hydrate="${hydrate}"${media ? ` data-media="${media}"` : ''} data-props='${escapeHtml(serializedProps)}' style="display:contents">${fallbackHtml}</div>`;
280
+ }
281
+
282
+ function escapeHtml(str: string): string {
283
+ return str
284
+ .replace(/&/g, '&amp;')
285
+ .replace(/'/g, '&#39;')
286
+ .replace(/"/g, '&quot;')
287
+ .replace(/</g, '&lt;')
288
+ .replace(/>/g, '&gt;');
289
+ }
290
+
291
+ function renderFallback(fallback: ReactNode): string {
292
+ // 간단한 fallback 처리 (실제로는 react-dom/server 사용)
293
+ if (typeof fallback === 'string') return fallback;
294
+ if (fallback === null || fallback === undefined) return '';
295
+ return '<div class="mandu-island-loading">Loading...</div>';
296
+ }
297
+
298
+ // ============================================================================
299
+ // Client Hydration Script
300
+ // ============================================================================
301
+
302
+ export const ISLAND_HYDRATION_SCRIPT = `
303
+ <script type="module">
304
+ (function() {
305
+ const strategies = {
306
+ load: (el, hydrate) => hydrate(),
307
+ idle: (el, hydrate) => {
308
+ if ('requestIdleCallback' in window) {
309
+ requestIdleCallback(hydrate);
310
+ } else {
311
+ setTimeout(hydrate, 200);
312
+ }
313
+ },
314
+ visible: (el, hydrate) => {
315
+ const observer = new IntersectionObserver((entries) => {
316
+ if (entries[0].isIntersecting) {
317
+ observer.disconnect();
318
+ hydrate();
319
+ }
320
+ });
321
+ // display:contents elements have zero size — observe first child instead
322
+ const target = (typeof getComputedStyle !== 'undefined' && getComputedStyle(el).display === 'contents' && el.firstElementChild) ? el.firstElementChild : el;
323
+ observer.observe(target);
324
+ },
325
+ media: (el, hydrate, query) => {
326
+ const mql = window.matchMedia(query);
327
+ if (mql.matches) {
328
+ hydrate();
329
+ } else {
330
+ mql.addEventListener('change', (e) => {
331
+ if (e.matches) hydrate();
332
+ }, { once: true });
333
+ }
334
+ },
335
+ never: () => {},
336
+ };
337
+
338
+ window.__MANDU_HYDRATE_ISLAND__ = async function(el, Component) {
339
+ const strategy = el.dataset.hydrate || 'load';
340
+ const media = el.dataset.media;
341
+ const props = JSON.parse(el.dataset.props || '{}');
342
+
343
+ const doHydrate = async () => {
344
+ const { createRoot } = await import('react-dom/client');
345
+ const root = createRoot(el);
346
+ root.render(window.React.createElement(Component, props));
347
+ el.dataset.hydrated = 'true';
348
+ console.log('[Mandu] Island hydrated:', el.dataset.manduIsland);
349
+ };
350
+
351
+ if (strategy === 'media' && media) {
352
+ strategies.media(el, doHydrate, media);
353
+ } else {
354
+ strategies[strategy]?.(el, doHydrate);
355
+ }
356
+ };
357
+
358
+ // Auto-discover and hydrate islands
359
+ document.querySelectorAll('[data-mandu-island]').forEach(el => {
360
+ const name = el.dataset.manduIsland;
361
+ if (window.__MANDU_ISLANDS__?.[name]) {
362
+ window.__MANDU_HYDRATE_ISLAND__(el, window.__MANDU_ISLANDS__[name]);
363
+ }
364
+ });
365
+ })();
366
+ </script>
367
+ `;
368
+
369
+ // ============================================================================
370
+ // Exports
371
+ // ============================================================================
372
+
373
+ export type { ComponentType, ReactNode };