@mandujs/core 0.9.41 → 0.9.43
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/README.ko.md +1 -1
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/bundler/build.ts +91 -73
- package/src/bundler/css.ts +283 -0
- package/src/bundler/dev.ts +31 -6
- package/src/bundler/index.ts +1 -0
- package/src/client/globals.ts +44 -0
- package/src/client/index.ts +5 -4
- package/src/client/island.ts +8 -13
- package/src/client/router.ts +33 -41
- package/src/client/runtime.ts +23 -51
- package/src/client/window-state.ts +101 -0
- package/src/config/index.ts +1 -0
- package/src/config/mandu.ts +45 -9
- package/src/config/validate.ts +158 -0
- package/src/constants.ts +25 -0
- package/src/contract/client.ts +4 -3
- package/src/contract/define.ts +459 -0
- package/src/devtools/ai/context-builder.ts +375 -0
- package/src/devtools/ai/index.ts +25 -0
- package/src/devtools/ai/mcp-connector.ts +465 -0
- package/src/devtools/client/catchers/error-catcher.ts +327 -0
- package/src/devtools/client/catchers/index.ts +18 -0
- package/src/devtools/client/catchers/network-proxy.ts +363 -0
- package/src/devtools/client/components/index.ts +39 -0
- package/src/devtools/client/components/kitchen-root.tsx +362 -0
- package/src/devtools/client/components/mandu-character.tsx +241 -0
- package/src/devtools/client/components/overlay.tsx +368 -0
- package/src/devtools/client/components/panel/errors-panel.tsx +259 -0
- package/src/devtools/client/components/panel/guard-panel.tsx +244 -0
- package/src/devtools/client/components/panel/index.ts +32 -0
- package/src/devtools/client/components/panel/islands-panel.tsx +304 -0
- package/src/devtools/client/components/panel/network-panel.tsx +292 -0
- package/src/devtools/client/components/panel/panel-container.tsx +259 -0
- package/src/devtools/client/filters/context-filters.ts +282 -0
- package/src/devtools/client/filters/index.ts +16 -0
- package/src/devtools/client/index.ts +63 -0
- package/src/devtools/client/persistence.ts +335 -0
- package/src/devtools/client/state-manager.ts +478 -0
- package/src/devtools/design-tokens.ts +263 -0
- package/src/devtools/hook/create-hook.ts +207 -0
- package/src/devtools/hook/index.ts +13 -0
- package/src/devtools/index.ts +439 -0
- package/src/devtools/init.ts +266 -0
- package/src/devtools/protocol.ts +237 -0
- package/src/devtools/server/index.ts +17 -0
- package/src/devtools/server/source-context.ts +444 -0
- package/src/devtools/types.ts +319 -0
- package/src/devtools/worker/index.ts +25 -0
- package/src/devtools/worker/redaction-worker.ts +222 -0
- package/src/devtools/worker/worker-manager.ts +409 -0
- package/src/error/formatter.ts +28 -24
- package/src/error/index.ts +13 -9
- package/src/error/result.ts +46 -0
- package/src/error/types.ts +6 -4
- package/src/filling/filling.ts +6 -5
- package/src/guard/check.ts +60 -56
- package/src/guard/types.ts +3 -1
- package/src/guard/watcher.ts +10 -1
- package/src/index.ts +81 -0
- package/src/intent/index.ts +310 -0
- package/src/island/index.ts +304 -0
- package/src/router/fs-patterns.ts +7 -0
- package/src/router/fs-routes.ts +20 -8
- package/src/router/fs-scanner.ts +117 -133
- package/src/runtime/server.ts +189 -61
- package/src/runtime/ssr.ts +14 -4
- package/src/runtime/streaming-ssr.ts +15 -4
- package/src/utils/bun.ts +8 -0
- package/src/utils/lru-cache.ts +75 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mandu Kitchen DevTools - Context Filters
|
|
3
|
+
* @version 1.0.3
|
|
4
|
+
*
|
|
5
|
+
* 마스킹 파이프라인 - PII/시크릿 정보 필터링
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { RedactPattern } from '../../types';
|
|
9
|
+
|
|
10
|
+
// ============================================================================
|
|
11
|
+
// Built-in Patterns
|
|
12
|
+
// ============================================================================
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 기본 제공 시크릿 패턴
|
|
16
|
+
*/
|
|
17
|
+
const BUILT_IN_SECRET_PATTERNS: RegExp[] = [
|
|
18
|
+
// JWT tokens
|
|
19
|
+
/eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/]*/g,
|
|
20
|
+
|
|
21
|
+
// AWS keys
|
|
22
|
+
/AKIA[0-9A-Z]{16}/g,
|
|
23
|
+
/[A-Za-z0-9/+=]{40}/g, // AWS secret (when near access key)
|
|
24
|
+
|
|
25
|
+
// API keys (generic patterns)
|
|
26
|
+
/api[_-]?key["\s:=]+["']?[A-Za-z0-9-_]{20,}["']?/gi,
|
|
27
|
+
/secret[_-]?key["\s:=]+["']?[A-Za-z0-9-_]{20,}["']?/gi,
|
|
28
|
+
|
|
29
|
+
// Private keys
|
|
30
|
+
/-----BEGIN [A-Z ]+ PRIVATE KEY-----[\s\S]*?-----END [A-Z ]+ PRIVATE KEY-----/g,
|
|
31
|
+
|
|
32
|
+
// Bearer tokens
|
|
33
|
+
/Bearer\s+[A-Za-z0-9-_.]+/gi,
|
|
34
|
+
|
|
35
|
+
// Basic auth
|
|
36
|
+
/Basic\s+[A-Za-z0-9+/=]+/gi,
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* PII 패턴 (이메일, 전화번호, IP 등)
|
|
41
|
+
*/
|
|
42
|
+
const PII_PATTERNS: RegExp[] = [
|
|
43
|
+
// Email
|
|
44
|
+
/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
|
|
45
|
+
|
|
46
|
+
// Phone numbers (다양한 형식)
|
|
47
|
+
/\b\d{3}[-.]?\d{3,4}[-.]?\d{4}\b/g,
|
|
48
|
+
/\+\d{1,3}[-.\s]?\(?\d{1,4}\)?[-.\s]?\d{1,4}[-.\s]?\d{1,9}/g,
|
|
49
|
+
|
|
50
|
+
// IPv4
|
|
51
|
+
/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
|
|
52
|
+
|
|
53
|
+
// IPv6
|
|
54
|
+
/([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}/g,
|
|
55
|
+
|
|
56
|
+
// Credit card (기본 형식만)
|
|
57
|
+
/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/g,
|
|
58
|
+
|
|
59
|
+
// SSN (US)
|
|
60
|
+
/\b\d{3}-\d{2}-\d{4}\b/g,
|
|
61
|
+
];
|
|
62
|
+
|
|
63
|
+
// ============================================================================
|
|
64
|
+
// Filter Functions
|
|
65
|
+
// ============================================================================
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Phase 1: 주석 제거
|
|
69
|
+
*/
|
|
70
|
+
export function removeComments(code: string): string {
|
|
71
|
+
// Single-line comments
|
|
72
|
+
let result = code.replace(/\/\/.*$/gm, '');
|
|
73
|
+
|
|
74
|
+
// Multi-line comments
|
|
75
|
+
result = result.replace(/\/\*[\s\S]*?\*\//g, '');
|
|
76
|
+
|
|
77
|
+
// HTML comments
|
|
78
|
+
result = result.replace(/<!--[\s\S]*?-->/g, '');
|
|
79
|
+
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Phase 1b: 문자열 처리
|
|
85
|
+
*
|
|
86
|
+
* @param mode
|
|
87
|
+
* - 'smart': PII/시크릿 패턴만 마스킹 (권장)
|
|
88
|
+
* - 'strip': 모든 문자열 제거
|
|
89
|
+
*/
|
|
90
|
+
export function handleStrings(code: string, mode: 'smart' | 'strip'): string {
|
|
91
|
+
if (mode === 'strip') {
|
|
92
|
+
// 모든 문자열 리터럴 제거
|
|
93
|
+
return code
|
|
94
|
+
.replace(/"(?:[^"\\]|\\.)*"/g, '"[STRING]"')
|
|
95
|
+
.replace(/'(?:[^'\\]|\\.)*'/g, "'[STRING]'")
|
|
96
|
+
.replace(/`(?:[^`\\]|\\.)*`/g, '`[STRING]`');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Smart mode: PII/시크릿만 마스킹
|
|
100
|
+
let result = code;
|
|
101
|
+
|
|
102
|
+
// 시크릿 패턴 마스킹
|
|
103
|
+
for (const pattern of BUILT_IN_SECRET_PATTERNS) {
|
|
104
|
+
result = result.replace(pattern, '[SECRET]');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// PII 패턴 마스킹
|
|
108
|
+
for (const pattern of PII_PATTERNS) {
|
|
109
|
+
result = result.replace(pattern, '[PII]');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Phase 2: 기본 보안 마스킹 (항상 적용, 비활성화 불가)
|
|
117
|
+
*/
|
|
118
|
+
export function redactBuiltInSecrets(text: string): string {
|
|
119
|
+
let result = text;
|
|
120
|
+
|
|
121
|
+
for (const pattern of BUILT_IN_SECRET_PATTERNS) {
|
|
122
|
+
// Reset regex state for global patterns
|
|
123
|
+
pattern.lastIndex = 0;
|
|
124
|
+
result = result.replace(pattern, '[REDACTED]');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Phase 3: 사용자 정의 패턴 적용 (옵트인)
|
|
132
|
+
*/
|
|
133
|
+
export function redactCustomPatterns(
|
|
134
|
+
text: string,
|
|
135
|
+
patterns: RedactPattern[]
|
|
136
|
+
): string {
|
|
137
|
+
let result = text;
|
|
138
|
+
|
|
139
|
+
for (const patternDef of patterns) {
|
|
140
|
+
try {
|
|
141
|
+
const regex = new RegExp(patternDef.source, patternDef.flags ?? 'gi');
|
|
142
|
+
const replacement = patternDef.replacement ?? '[REDACTED]';
|
|
143
|
+
result = result.replace(regex, replacement);
|
|
144
|
+
} catch (e) {
|
|
145
|
+
// 잘못된 정규식은 무시
|
|
146
|
+
console.warn(
|
|
147
|
+
`[Mandu Kitchen] Invalid redact pattern: ${patternDef.source}`,
|
|
148
|
+
e
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Phase 4: 용량 제한 (항상 마지막)
|
|
158
|
+
*/
|
|
159
|
+
export function truncate(text: string, maxBytes: number): string {
|
|
160
|
+
if (maxBytes <= 0) return text;
|
|
161
|
+
|
|
162
|
+
// UTF-8 바이트 길이 계산
|
|
163
|
+
const encoder = new TextEncoder();
|
|
164
|
+
const encoded = encoder.encode(text);
|
|
165
|
+
|
|
166
|
+
if (encoded.length <= maxBytes) {
|
|
167
|
+
return text;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 바이트 단위로 자르고 디코딩
|
|
171
|
+
const truncated = encoded.slice(0, maxBytes);
|
|
172
|
+
const decoder = new TextDecoder('utf-8', { fatal: false });
|
|
173
|
+
let result = decoder.decode(truncated);
|
|
174
|
+
|
|
175
|
+
// 잘린 멀티바이트 문자 처리 (마지막 불완전한 문자 제거)
|
|
176
|
+
if (result.endsWith('\ufffd')) {
|
|
177
|
+
result = result.slice(0, -1);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return result + '... [TRUNCATED]';
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ============================================================================
|
|
184
|
+
// Context Filters Pipeline
|
|
185
|
+
// ============================================================================
|
|
186
|
+
|
|
187
|
+
export interface FilterOptions {
|
|
188
|
+
/** 문자열 처리 모드 */
|
|
189
|
+
stringMode?: 'smart' | 'strip';
|
|
190
|
+
/** 사용자 정의 패턴 */
|
|
191
|
+
customPatterns?: RedactPattern[];
|
|
192
|
+
/** 최대 바이트 */
|
|
193
|
+
maxBytes?: number;
|
|
194
|
+
/** 주석 제거 여부 (기본: true) */
|
|
195
|
+
removeComments?: boolean;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* 전체 필터 파이프라인 실행
|
|
200
|
+
*/
|
|
201
|
+
export function applyContextFilters(
|
|
202
|
+
text: string,
|
|
203
|
+
options: FilterOptions = {}
|
|
204
|
+
): string {
|
|
205
|
+
const {
|
|
206
|
+
stringMode = 'smart',
|
|
207
|
+
customPatterns = [],
|
|
208
|
+
maxBytes = 50_000, // 50KB default
|
|
209
|
+
removeComments: shouldRemoveComments = true,
|
|
210
|
+
} = options;
|
|
211
|
+
|
|
212
|
+
let result = text;
|
|
213
|
+
|
|
214
|
+
// Phase 1: 주석 제거
|
|
215
|
+
if (shouldRemoveComments) {
|
|
216
|
+
result = removeComments(result);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Phase 1b: 문자열 처리
|
|
220
|
+
result = handleStrings(result, stringMode);
|
|
221
|
+
|
|
222
|
+
// Phase 2: 기본 보안 마스킹 (항상 적용)
|
|
223
|
+
result = redactBuiltInSecrets(result);
|
|
224
|
+
|
|
225
|
+
// Phase 3: 사용자 정의 패턴
|
|
226
|
+
if (customPatterns.length > 0) {
|
|
227
|
+
result = redactCustomPatterns(result, customPatterns);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Phase 4: 용량 제한 (항상 마지막)
|
|
231
|
+
result = truncate(result, maxBytes);
|
|
232
|
+
|
|
233
|
+
return result;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ============================================================================
|
|
237
|
+
// Stack Trace Sanitizer
|
|
238
|
+
// ============================================================================
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* 스택 트레이스에서 민감 정보 제거
|
|
242
|
+
*/
|
|
243
|
+
export function sanitizeStackTrace(stack: string | undefined): string | undefined {
|
|
244
|
+
if (!stack) return undefined;
|
|
245
|
+
|
|
246
|
+
let result = stack;
|
|
247
|
+
|
|
248
|
+
// 파일 경로에서 사용자명 제거
|
|
249
|
+
result = result.replace(/\/Users\/[^/]+\//g, '/Users/[USER]/');
|
|
250
|
+
result = result.replace(/\\Users\\[^\\]+\\/g, '\\Users\\[USER]\\');
|
|
251
|
+
result = result.replace(/\/home\/[^/]+\//g, '/home/[USER]/');
|
|
252
|
+
|
|
253
|
+
// 쿼리스트링 파라미터 마스킹
|
|
254
|
+
result = result.replace(/\?[^\s)]+/g, '?[PARAMS]');
|
|
255
|
+
|
|
256
|
+
// 기본 시크릿 마스킹
|
|
257
|
+
result = redactBuiltInSecrets(result);
|
|
258
|
+
|
|
259
|
+
return result;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ============================================================================
|
|
263
|
+
// Error Message Sanitizer
|
|
264
|
+
// ============================================================================
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* 에러 메시지에서 민감 정보 제거
|
|
268
|
+
*/
|
|
269
|
+
export function sanitizeErrorMessage(message: string): string {
|
|
270
|
+
let result = message;
|
|
271
|
+
|
|
272
|
+
// PII 마스킹
|
|
273
|
+
for (const pattern of PII_PATTERNS) {
|
|
274
|
+
pattern.lastIndex = 0;
|
|
275
|
+
result = result.replace(pattern, '[PII]');
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// 시크릿 마스킹
|
|
279
|
+
result = redactBuiltInSecrets(result);
|
|
280
|
+
|
|
281
|
+
return result;
|
|
282
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mandu Kitchen DevTools - Filters Module
|
|
3
|
+
* @version 1.0.3
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export {
|
|
7
|
+
removeComments,
|
|
8
|
+
handleStrings,
|
|
9
|
+
redactBuiltInSecrets,
|
|
10
|
+
redactCustomPatterns,
|
|
11
|
+
truncate,
|
|
12
|
+
applyContextFilters,
|
|
13
|
+
sanitizeStackTrace,
|
|
14
|
+
sanitizeErrorMessage,
|
|
15
|
+
type FilterOptions,
|
|
16
|
+
} from './context-filters';
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mandu Kitchen DevTools - Client Module
|
|
3
|
+
* @version 1.0.3
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// State Management
|
|
7
|
+
export {
|
|
8
|
+
KitchenStateManager,
|
|
9
|
+
getStateManager,
|
|
10
|
+
resetStateManager,
|
|
11
|
+
type KitchenState,
|
|
12
|
+
type StateListener,
|
|
13
|
+
} from './state-manager';
|
|
14
|
+
|
|
15
|
+
// Error Catching
|
|
16
|
+
export {
|
|
17
|
+
ErrorCatcher,
|
|
18
|
+
getErrorCatcher,
|
|
19
|
+
initializeErrorCatcher,
|
|
20
|
+
destroyErrorCatcher,
|
|
21
|
+
} from './catchers';
|
|
22
|
+
|
|
23
|
+
// Network Proxy
|
|
24
|
+
export {
|
|
25
|
+
NetworkProxy,
|
|
26
|
+
getNetworkProxy,
|
|
27
|
+
initializeNetworkProxy,
|
|
28
|
+
destroyNetworkProxy,
|
|
29
|
+
} from './catchers';
|
|
30
|
+
|
|
31
|
+
// Filters
|
|
32
|
+
export {
|
|
33
|
+
removeComments,
|
|
34
|
+
handleStrings,
|
|
35
|
+
redactBuiltInSecrets,
|
|
36
|
+
redactCustomPatterns,
|
|
37
|
+
truncate,
|
|
38
|
+
applyContextFilters,
|
|
39
|
+
sanitizeStackTrace,
|
|
40
|
+
sanitizeErrorMessage,
|
|
41
|
+
type FilterOptions,
|
|
42
|
+
} from './filters';
|
|
43
|
+
|
|
44
|
+
// Persistence
|
|
45
|
+
export {
|
|
46
|
+
PersistenceManager,
|
|
47
|
+
getPersistenceManager,
|
|
48
|
+
initializePersistence,
|
|
49
|
+
destroyPersistence,
|
|
50
|
+
} from './persistence';
|
|
51
|
+
|
|
52
|
+
// Components
|
|
53
|
+
export {
|
|
54
|
+
ManduCharacter,
|
|
55
|
+
ManduBadge,
|
|
56
|
+
ErrorOverlay,
|
|
57
|
+
mountKitchen,
|
|
58
|
+
unmountKitchen,
|
|
59
|
+
isKitchenMounted,
|
|
60
|
+
type ManduCharacterProps,
|
|
61
|
+
type ManduBadgeProps,
|
|
62
|
+
type ErrorOverlayProps,
|
|
63
|
+
} from './components';
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mandu Kitchen DevTools - Persistence
|
|
3
|
+
* @version 1.0.3
|
|
4
|
+
*
|
|
5
|
+
* sessionStorage를 사용한 이벤트 영속화
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { KitchenEvent, PreserveLogConfig, KitchenMetaLog } from '../types';
|
|
9
|
+
|
|
10
|
+
// ============================================================================
|
|
11
|
+
// Constants
|
|
12
|
+
// ============================================================================
|
|
13
|
+
|
|
14
|
+
const STORAGE_KEY = 'mandu-kitchen-events';
|
|
15
|
+
const META_LOG_KEY = 'mandu-kitchen-meta';
|
|
16
|
+
const MAX_META_LOGS = 20;
|
|
17
|
+
|
|
18
|
+
const DEFAULT_CONFIG: PreserveLogConfig = {
|
|
19
|
+
enabled: true,
|
|
20
|
+
maxPersistEvents: 50,
|
|
21
|
+
maxPersistBytes: 2_000_000, // 2MB
|
|
22
|
+
priority: 'errors-first',
|
|
23
|
+
incremental: {
|
|
24
|
+
enabled: true,
|
|
25
|
+
idleSyncMs: 300,
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// ============================================================================
|
|
30
|
+
// Persistence Manager
|
|
31
|
+
// ============================================================================
|
|
32
|
+
|
|
33
|
+
export class PersistenceManager {
|
|
34
|
+
private config: PreserveLogConfig;
|
|
35
|
+
private pendingEvents: KitchenEvent[] = [];
|
|
36
|
+
private syncTimeoutId: number | null = null;
|
|
37
|
+
private isEnabled = true;
|
|
38
|
+
|
|
39
|
+
constructor(config?: Partial<PreserveLogConfig>) {
|
|
40
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// --------------------------------------------------------------------------
|
|
44
|
+
// Configuration
|
|
45
|
+
// --------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
updateConfig(config: Partial<PreserveLogConfig>): void {
|
|
48
|
+
this.config = { ...this.config, ...config };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
setEnabled(enabled: boolean): void {
|
|
52
|
+
this.isEnabled = enabled;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// --------------------------------------------------------------------------
|
|
56
|
+
// Event Management
|
|
57
|
+
// --------------------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 이벤트 추가
|
|
61
|
+
*/
|
|
62
|
+
addEvent(event: KitchenEvent): void {
|
|
63
|
+
if (!this.config.enabled || !this.isEnabled) return;
|
|
64
|
+
|
|
65
|
+
this.pendingEvents.push(event);
|
|
66
|
+
|
|
67
|
+
// Incremental sync
|
|
68
|
+
if (this.config.incremental?.enabled) {
|
|
69
|
+
this.scheduleSync();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 여러 이벤트 추가
|
|
75
|
+
*/
|
|
76
|
+
addEvents(events: KitchenEvent[]): void {
|
|
77
|
+
if (!this.config.enabled || !this.isEnabled) return;
|
|
78
|
+
|
|
79
|
+
this.pendingEvents.push(...events);
|
|
80
|
+
|
|
81
|
+
if (this.config.incremental?.enabled) {
|
|
82
|
+
this.scheduleSync();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 즉시 저장
|
|
88
|
+
*/
|
|
89
|
+
flush(): void {
|
|
90
|
+
if (this.syncTimeoutId) {
|
|
91
|
+
clearTimeout(this.syncTimeoutId);
|
|
92
|
+
this.syncTimeoutId = null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
this.persistEvents();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// --------------------------------------------------------------------------
|
|
99
|
+
// Sync Scheduling
|
|
100
|
+
// --------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
private scheduleSync(): void {
|
|
103
|
+
if (this.syncTimeoutId) return;
|
|
104
|
+
|
|
105
|
+
const idleSyncMs = this.config.incremental?.idleSyncMs ?? 300;
|
|
106
|
+
|
|
107
|
+
this.syncTimeoutId = window.setTimeout(() => {
|
|
108
|
+
this.syncTimeoutId = null;
|
|
109
|
+
this.persistEvents();
|
|
110
|
+
}, idleSyncMs);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// --------------------------------------------------------------------------
|
|
114
|
+
// Persistence
|
|
115
|
+
// --------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
private persistEvents(): void {
|
|
118
|
+
if (this.pendingEvents.length === 0) return;
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
// 기존 이벤트 로드
|
|
122
|
+
const existingEvents = this.loadEvents();
|
|
123
|
+
|
|
124
|
+
// 새 이벤트 병합
|
|
125
|
+
const allEvents = [...existingEvents, ...this.pendingEvents];
|
|
126
|
+
|
|
127
|
+
// 우선순위에 따라 정렬
|
|
128
|
+
const sorted = this.sortByPriority(allEvents);
|
|
129
|
+
|
|
130
|
+
// 저장 시도
|
|
131
|
+
this.saveEvents(sorted);
|
|
132
|
+
|
|
133
|
+
// 성공 시 pending 클리어
|
|
134
|
+
this.pendingEvents = [];
|
|
135
|
+
} catch (e) {
|
|
136
|
+
this.logMeta({
|
|
137
|
+
timestamp: Date.now(),
|
|
138
|
+
type: 'persist_fail',
|
|
139
|
+
error: e instanceof Error ? e.message : String(e),
|
|
140
|
+
context: {
|
|
141
|
+
eventCount: this.pendingEvents.length,
|
|
142
|
+
activeTab: 'unknown',
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private sortByPriority(events: KitchenEvent[]): KitchenEvent[] {
|
|
149
|
+
const sorted = [...events];
|
|
150
|
+
|
|
151
|
+
if (this.config.priority === 'errors-first') {
|
|
152
|
+
sorted.sort((a, b) => {
|
|
153
|
+
const aIsError = a.type === 'error' ? 1 : 0;
|
|
154
|
+
const bIsError = b.type === 'error' ? 1 : 0;
|
|
155
|
+
|
|
156
|
+
if (aIsError !== bIsError) {
|
|
157
|
+
return bIsError - aIsError; // 에러 우선
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return b.timestamp - a.timestamp; // 최신 우선
|
|
161
|
+
});
|
|
162
|
+
} else {
|
|
163
|
+
// recent-first
|
|
164
|
+
sorted.sort((a, b) => b.timestamp - a.timestamp);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return sorted;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
private saveEvents(events: KitchenEvent[]): void {
|
|
171
|
+
const { maxPersistEvents, maxPersistBytes } = this.config;
|
|
172
|
+
|
|
173
|
+
// 최대 개수 제한
|
|
174
|
+
let subset = events.slice(0, maxPersistEvents);
|
|
175
|
+
|
|
176
|
+
// 바이트 제한에 맞게 조정
|
|
177
|
+
for (let i = subset.length; i > 0; i--) {
|
|
178
|
+
try {
|
|
179
|
+
const toSave = subset.slice(0, i);
|
|
180
|
+
const json = JSON.stringify(toSave);
|
|
181
|
+
|
|
182
|
+
if (json.length > maxPersistBytes) {
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
sessionStorage.setItem(STORAGE_KEY, json);
|
|
187
|
+
return;
|
|
188
|
+
} catch (e) {
|
|
189
|
+
if (e instanceof DOMException && e.name === 'QuotaExceededError') {
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
throw e;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// 모두 실패 시 스토리지 클리어
|
|
197
|
+
sessionStorage.removeItem(STORAGE_KEY);
|
|
198
|
+
this.logMeta({
|
|
199
|
+
timestamp: Date.now(),
|
|
200
|
+
type: 'persist_fail',
|
|
201
|
+
error: 'All save attempts failed, storage cleared',
|
|
202
|
+
context: {
|
|
203
|
+
eventCount: events.length,
|
|
204
|
+
activeTab: 'unknown',
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// --------------------------------------------------------------------------
|
|
210
|
+
// Load
|
|
211
|
+
// --------------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 저장된 이벤트 로드
|
|
215
|
+
*/
|
|
216
|
+
loadEvents(): KitchenEvent[] {
|
|
217
|
+
try {
|
|
218
|
+
const json = sessionStorage.getItem(STORAGE_KEY);
|
|
219
|
+
if (!json) return [];
|
|
220
|
+
|
|
221
|
+
const events = JSON.parse(json) as KitchenEvent[];
|
|
222
|
+
return Array.isArray(events) ? events : [];
|
|
223
|
+
} catch {
|
|
224
|
+
return [];
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 저장된 이벤트 클리어
|
|
230
|
+
*/
|
|
231
|
+
clearEvents(): void {
|
|
232
|
+
sessionStorage.removeItem(STORAGE_KEY);
|
|
233
|
+
this.pendingEvents = [];
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// --------------------------------------------------------------------------
|
|
237
|
+
// Meta Logging
|
|
238
|
+
// --------------------------------------------------------------------------
|
|
239
|
+
|
|
240
|
+
private logMeta(log: KitchenMetaLog): void {
|
|
241
|
+
try {
|
|
242
|
+
const existingJson = sessionStorage.getItem(META_LOG_KEY);
|
|
243
|
+
const existing: KitchenMetaLog[] = existingJson
|
|
244
|
+
? JSON.parse(existingJson)
|
|
245
|
+
: [];
|
|
246
|
+
|
|
247
|
+
existing.push(log);
|
|
248
|
+
|
|
249
|
+
// 최대 개수 제한
|
|
250
|
+
const trimmed = existing.slice(-MAX_META_LOGS);
|
|
251
|
+
|
|
252
|
+
sessionStorage.setItem(META_LOG_KEY, JSON.stringify(trimmed));
|
|
253
|
+
} catch {
|
|
254
|
+
// 메타 로깅 실패는 무시
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* 메타 로그 조회
|
|
260
|
+
*/
|
|
261
|
+
getMetaLogs(): KitchenMetaLog[] {
|
|
262
|
+
try {
|
|
263
|
+
const json = sessionStorage.getItem(META_LOG_KEY);
|
|
264
|
+
if (!json) return [];
|
|
265
|
+
|
|
266
|
+
const logs = JSON.parse(json) as KitchenMetaLog[];
|
|
267
|
+
return Array.isArray(logs) ? logs : [];
|
|
268
|
+
} catch {
|
|
269
|
+
return [];
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 메타 로그 클리어
|
|
275
|
+
*/
|
|
276
|
+
clearMetaLogs(): void {
|
|
277
|
+
sessionStorage.removeItem(META_LOG_KEY);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// --------------------------------------------------------------------------
|
|
281
|
+
// Lifecycle
|
|
282
|
+
// --------------------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* beforeunload 이벤트에 연결
|
|
286
|
+
*/
|
|
287
|
+
attachBeforeUnload(): () => void {
|
|
288
|
+
const handler = () => {
|
|
289
|
+
this.flush();
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
window.addEventListener('beforeunload', handler);
|
|
293
|
+
|
|
294
|
+
return () => {
|
|
295
|
+
window.removeEventListener('beforeunload', handler);
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* 정리
|
|
301
|
+
*/
|
|
302
|
+
destroy(): void {
|
|
303
|
+
if (this.syncTimeoutId) {
|
|
304
|
+
clearTimeout(this.syncTimeoutId);
|
|
305
|
+
this.syncTimeoutId = null;
|
|
306
|
+
}
|
|
307
|
+
this.pendingEvents = [];
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// ============================================================================
|
|
312
|
+
// Singleton Instance
|
|
313
|
+
// ============================================================================
|
|
314
|
+
|
|
315
|
+
let globalPersistence: PersistenceManager | null = null;
|
|
316
|
+
|
|
317
|
+
export function getPersistenceManager(config?: Partial<PreserveLogConfig>): PersistenceManager {
|
|
318
|
+
if (!globalPersistence) {
|
|
319
|
+
globalPersistence = new PersistenceManager(config);
|
|
320
|
+
}
|
|
321
|
+
return globalPersistence;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export function initializePersistence(config?: Partial<PreserveLogConfig>): PersistenceManager {
|
|
325
|
+
const manager = getPersistenceManager(config);
|
|
326
|
+
manager.attachBeforeUnload();
|
|
327
|
+
return manager;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export function destroyPersistence(): void {
|
|
331
|
+
if (globalPersistence) {
|
|
332
|
+
globalPersistence.destroy();
|
|
333
|
+
globalPersistence = null;
|
|
334
|
+
}
|
|
335
|
+
}
|