-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlabel-line-mapper.ts
More file actions
322 lines (294 loc) · 9.14 KB
/
Copy pathlabel-line-mapper.ts
File metadata and controls
322 lines (294 loc) · 9.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/**
* Label Line Mapper
*
* Shared utilities for mapping RPY parser entries to label_lines database values.
* Extracted to eliminate code duplication between gitlab-sync, label-sync, and gitlab-file-sync services.
*/
import { calculateContentHash } from "../lib/hash.js";
import type { NewLabelLine } from "../db/schema/index.js";
import { ValidationError } from "../middleware/error-handler.middleware.js";
import { logError, LogEventType } from "../lib/logger.js";
import type {
ComparisonOperator,
StatCondition,
VariableCondition,
} from "@branchforge/shared";
// ============================================================================
// Type Definitions
// ============================================================================
/**
* Supported content types for label lines
* Matches the database enum for label_lines.contentType
*/
export type ContentType =
| "NARRATION"
| "DIALOGUE"
| "CHOICE"
| "MENU"
| "JUMP"
| "FLAG";
/**
* Type for line-level conditions
*/
export type LineConditions = {
stats?: Record<string, number | StatCondition>;
variables?: Record<string, VariableCondition>;
statDeltas?: Record<string, number>;
};
/**
* Type for visual statements (scene, show, hide)
*/
export type VisualStatement = {
type: "SCENE" | "SHOW" | "HIDE";
target: string;
at?: string;
with?: string;
zorder?: number;
};
/**
* Strict content types for label sync operations
* Subset of ContentType that excludes CHOICE and MENU
*/
export type StrictContentType = "NARRATION" | "DIALOGUE" | "JUMP";
/**
* Type for label line insert values
* Inferred from the label_lines table schema to stay in sync
*/
export type LabelLineInsertValues = Pick<
NewLabelLine,
| "labelId"
| "sequence"
| "contentType"
| "content"
| "speakerId"
| "projectFileId"
| "linePosition"
| "contentHash"
| "lastSyncedHash"
| "lastSyncedAt"
| "rpyLineNumber"
| "rpyIndentLevel"
| "conditions"
| "visualStatements"
| "menuOptions"
>;
// ============================================================================
// Constants
// ============================================================================
/**
* Content type constant for FLAG entries
* FLAG is mapped to JUMP for database storage
*/
const FLAG_MAPPED_TYPE: StrictContentType = "JUMP";
/**
* Default fallback content type when entry type is unrecognized
*/
const DEFAULT_CONTENT_TYPE: StrictContentType = "NARRATION";
/**
* Default operator for stat conditions when not explicitly specified
*/
const DEFAULT_OPERATOR: ComparisonOperator = ">=";
// ============================================================================
// Type Mapping Functions
// ============================================================================
/**
* Check if an entry type is a recognized strict content type
*
* @param type - Entry type string to check
* @returns True if the type is NARRATION, DIALOGUE, or JUMP
*/
function isStrictContentType(type: string): type is StrictContentType {
return type === "NARRATION" || type === "DIALOGUE" || type === "JUMP";
}
/**
* Normalize a stat condition to ensure it has the correct shape.
* Converts plain numbers to StatCondition objects with the default operator.
*
* @param value - Either a number or a StatCondition object
* @returns A normalized StatCondition object
*/
function normalizeStatCondition(value: number | StatCondition): StatCondition {
if (typeof value === "number") {
return { value, operator: DEFAULT_OPERATOR };
}
return value;
}
/**
* Normalize line conditions to ensure all stats are StatCondition objects.
*
* @param conditions - LineConditions object to normalize
* @returns Normalized LineConditions with StatCondition objects for stats
*/
function normalizeLineConditions(
conditions?: LineConditions
): LineConditions | undefined {
if (!conditions?.stats) return conditions;
const normalized: Record<string, StatCondition> = {};
for (const [key, value] of Object.entries(conditions.stats)) {
normalized[key] = normalizeStatCondition(value);
}
return { ...conditions, stats: normalized };
}
/**
* Map entry type to content type with fallback
* Handles FLAG entries and provides default fallback for unrecognized types
*
* @param entry - Parsed entry from RPY file
* @returns Object with contentType and formatted content string
*/
export function mapEntryToDbContentType(entry: {
type: ContentType;
text?: string;
target?: string;
}): {
contentType: StrictContentType;
content: string;
} {
// Map FLAG to JUMP
if (entry.type === "FLAG") {
const content = entry.target ? `jump ${entry.target}` : "";
return { contentType: FLAG_MAPPED_TYPE, content };
}
// Use strict content types if recognized, otherwise default to NARRATION
let contentType: StrictContentType;
if (isStrictContentType(entry.type)) {
contentType = entry.type as StrictContentType;
} else {
contentType = DEFAULT_CONTENT_TYPE;
}
// Format content for JUMP entries with targets
const content =
entry.target && contentType === "JUMP"
? `jump ${entry.target}`
: (entry.text ?? "");
return { contentType, content };
}
/**
* Map entry type to strict content type
* Throws error on unrecognized types - use when validation is required
*
* @param entry - Parsed entry from RPY file
* @returns Strict content type enum value
* @throws Error if entry type is not recognized
*/
export function mapEntryToDbType(entry: {
type: ContentType;
}): StrictContentType {
// Map FLAG to JUMP
if (entry.type === "FLAG") {
return FLAG_MAPPED_TYPE;
}
// Validate and return strict content type
if (isStrictContentType(entry.type)) {
return entry.type as StrictContentType;
}
// Don't default to NARRATION - fail explicitly on unrecognized types
// This prevents non-dialogue entries from becoming label_lines
logError(LogEventType.SERVICE_ERROR, {
message: `Unrecognized entry type: ${entry.type}`,
});
throw new ValidationError("Invalid content type");
}
/**
* Helper function to get character ID by renpyTag
* Returns null if character not found
* Performs exact match first, then falls back to case-insensitive lookup.
*
* @param renpyTag - Character's Ren'Py tag
* @param charactersByTag - Map of renpyTag to character ID
* @returns Character ID or null
*/
export function getCharacterIdByTag(
renpyTag: string | undefined,
charactersByTag: Map<string, string>
): string | null {
if (!renpyTag) return null;
const exact = charactersByTag.get(renpyTag);
if (exact) return exact;
const lower = renpyTag.toLowerCase();
for (const [key, value] of charactersByTag) {
if (key.toLowerCase() === lower) return value;
}
return null;
}
/**
* Helper function to map parsed entries to LabelLineInsertValues
* Consolidates logic from gitlab-sync, label-sync, and gitlab-file-sync services
*
* @param entries - Array of parsed entries from RPY file
* @param labelId - Label ID to associate lines with
* @param projectFileId - Project file ID
* @param charactersByTag - Map of renpyTag to character ID for speaker resolution
* @returns Array of LabelLineInsertValues ready for database insertion
*/
export function mapEntriesToLabelLineValues(
entries: Array<{
type: ContentType;
text?: string;
target?: string;
speaker?: string;
lineNumber?: number;
indentLevel?: number;
conditions?: LineConditions;
visuals?: VisualStatement[];
menuOptions?: Array<{
label: string;
targetLabelId: string;
targetLabelName: string;
conditionFlags?: string[];
effects?: {
stats?: Record<string, number>;
};
}>;
}>,
labelId: string,
projectFileId: string,
charactersByTag: Map<string, string>
): LabelLineInsertValues[] {
return entries.map((entry, index) => {
// Handle MENU entries with menuOptions
if (entry.type === "MENU") {
const contentHash = calculateContentHash(
JSON.stringify(entry.menuOptions ?? [])
);
return {
labelId,
sequence: index + 1,
contentType: "MENU" as const,
content: "",
speakerId: null,
projectFileId,
linePosition: index,
contentHash,
lastSyncedHash: contentHash,
lastSyncedAt: new Date(),
rpyLineNumber: entry.lineNumber,
rpyIndentLevel: entry.indentLevel ?? 0,
conditions: null,
visualStatements: null,
menuOptions: entry.menuOptions ?? null,
};
}
const mapped = mapEntryToDbContentType(entry);
const entryContentHash = calculateContentHash(mapped.content);
const speakerId = getCharacterIdByTag(entry.speaker, charactersByTag);
const normalizedConditions = normalizeLineConditions(entry.conditions);
return {
labelId,
sequence: index + 1,
contentType: mapped.contentType,
content: mapped.content,
speakerId,
projectFileId,
linePosition: index,
contentHash: entryContentHash,
lastSyncedHash: entryContentHash,
lastSyncedAt: new Date(),
rpyLineNumber: entry.lineNumber,
rpyIndentLevel: entry.indentLevel ?? 0,
conditions: normalizedConditions ?? null,
visualStatements: entry.visuals ?? null,
menuOptions: null,
};
});
}