or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-extraction.mdindex.mdmessage-bundle.mdserializers.mdtranslation-service.md

message-bundle.mddocs/

0

# Message Bundle Management

1

2

Manages i18n message collections with support for template processing, message extraction, and translation file generation.

3

4

## Capabilities

5

6

### MessageBundle Class

7

8

Central class for managing collections of i18n messages with template processing and serialization capabilities.

9

10

```typescript { .api }

11

/**

12

* Manages a collection of i18n messages for a specific locale

13

* Provides methods for adding messages from templates and generating translation files

14

*/

15

class MessageBundle {

16

/**

17

* Creates a new MessageBundle instance

18

* @param locale - Optional locale string (default: null)

19

*/

20

constructor(locale?: string | null);

21

22

/**

23

* Adds messages from a template string or I18nDef object

24

* Parses the template for translatable content and extracts messages

25

* @param template - Template string or I18nDef object containing translatable content

26

* @param url - Source file URL/path for tracking message origins

27

* @returns Array of extracted i18n.Message objects

28

*/

29

updateFromTemplate(template: string | I18nDef, url: string): i18n.Message[];

30

31

/**

32

* Returns all messages currently in the bundle

33

* @returns Array of all i18n.Message objects in the bundle

34

*/

35

getMessages(): i18n.Message[];

36

37

/**

38

* Generates translation file content using specified serializer

39

* @param write - Serializer write function (e.g., xliffWrite, xliff2Write)

40

* @param digest - Digest function for message ID generation

41

* @param xmlMessagesById - Optional existing XML messages to merge

42

* @param createMapper - Optional placeholder mapper factory function

43

* @param filterSources - Optional source filtering function

44

* @returns Generated translation file content as string

45

*/

46

write(

47

write: (messages: i18n.Message[], locale: string | null, existingNodes?: xml.Node[]) => string,

48

digest: (message: i18n.Message) => string,

49

xmlMessagesById?: {[id: string]: xml.Node},

50

createMapper?: (message: i18n.Message) => PlaceholderMapper,

51

filterSources?: (path: string) => string

52

): string;

53

}

54

```

55

56

### HtmlParser Class

57

58

Parses HTML templates to extract i18n messages and handle translation merging.

59

60

```typescript { .api }

61

/**

62

* Parser for HTML templates with i18n message extraction capabilities

63

*/

64

class HtmlParser {

65

/**

66

* Creates a new HtmlParser instance with default interpolation configuration

67

*/

68

constructor();

69

70

/**

71

* Parses HTML content and extracts structure

72

* @param source - HTML source code to parse

73

* @param url - Source URL/path for error reporting

74

* @param parseExpansionForms - Whether to parse ICU expressions (default: false)

75

* @returns Parse result with nodes and any errors

76

*/

77

parse(source: string, url: string, parseExpansionForms?: boolean): html.ParseTreeResult;

78

79

/**

80

* Merges translations into parsed HTML nodes

81

* @param rootNodes - Parsed HTML root nodes

82

* @param translations - Translation bundle with message mappings

83

* @param params - Interpolation parameters

84

* @param metadata - Message metadata (id, meaning, description)

85

* @param implicitTags - Array of implicit HTML tags to handle

86

* @returns Merged nodes with translations applied

87

*/

88

mergeTranslations(

89

rootNodes: html.Node[],

90

translations: TranslationBundle,

91

params: {[key: string]: any},

92

metadata: MessageMetadata,

93

implicitTags: string[]

94

): ExtractionResult;

95

}

96

```

97

98

### TranslationBundle Class

99

100

Manages loaded translation data and provides translation lookup capabilities.

101

102

```typescript { .api }

103

/**

104

* Container for loaded translation data with message lookup capabilities

105

*/

106

class TranslationBundle {

107

/**

108

* Loads translation data from various sources

109

* @param translations - Translation file content string

110

* @param url - Source URL for the translations

111

* @param digest - Message digest function

112

* @param createMapper - Placeholder mapper factory function

113

* @param loadFct - Loader function to parse translation content

114

* @param missingTranslationStrategy - Strategy for handling missing translations

115

* @returns TranslationBundle instance with loaded translations

116

*/

117

static load(

118

translations: string,

119

url: string,

120

digest: (message: i18n.Message) => string,

121

createMapper: (message: i18n.Message) => PlaceholderMapper,

122

loadFct: (content: string, url: string) => I18nMessagesById,

123

missingTranslationStrategy: MissingTranslationStrategy

124

): TranslationBundle;

125

126

/**

127

* Retrieves translation for a message

128

* @param srcMsg - Source message to translate

129

* @returns Translated message or null if not found

130

*/

131

get(srcMsg: i18n.Message): i18n.Message | null;

132

133

/**

134

* Checks if a translation exists for a message

135

* @param srcMsg - Source message to check

136

* @returns True if translation exists, false otherwise

137

*/

138

has(srcMsg: i18n.Message): boolean;

139

}

140

```

141

142

### ExtractionResult Class

143

144

Contains results from message extraction operations.

145

146

```typescript { .api }

147

/**

148

* Results from i18n message extraction operations

149

*/

150

class ExtractionResult {

151

constructor(

152

rootNodes: html.Node[],

153

errors: i18n.I18nError[]

154

);

155

156

/** Extracted/processed HTML nodes */

157

rootNodes: html.Node[];

158

159

/** Any errors encountered during extraction */

160

errors: i18n.I18nError[];

161

}

162

```

163

164

## Usage Examples

165

166

### Basic Message Bundle Usage

167

168

```typescript

169

import { MessageBundle } from "@ngx-translate/i18n-polyfill/extractor";

170

import { xliffWrite, xliffDigest } from "@ngx-translate/i18n-polyfill/serializers";

171

172

// Create a message bundle for English locale

173

const bundle = new MessageBundle("en");

174

175

// Add simple string messages

176

bundle.updateFromTemplate("Hello world", "app.component.ts");

177

bundle.updateFromTemplate("Welcome to our application", "home.component.ts");

178

179

// Add messages with interpolation

180

bundle.updateFromTemplate("Hello {{name}}", "greeting.component.ts");

181

182

// Add I18nDef objects with metadata

183

bundle.updateFromTemplate({

184

value: "You have {{count}} new messages",

185

id: "notification.count",

186

meaning: "notification",

187

description: "Shows count of new messages to user"

188

}, "notification.component.ts");

189

190

// Get all messages

191

const messages = bundle.getMessages();

192

console.log(`Extracted ${messages.length} messages`);

193

194

// Generate XLIFF translation file

195

const xliffContent = bundle.write(xliffWrite, xliffDigest);

196

console.log(xliffContent);

197

```

198

199

### HTML Template Processing

200

201

```typescript

202

import { HtmlParser, TranslationBundle } from "@ngx-translate/i18n-polyfill/parser";

203

import { xliffLoadToI18n, xliffDigest } from "@ngx-translate/i18n-polyfill/serializers";

204

205

// Parse HTML template

206

const parser = new HtmlParser();

207

const parseResult = parser.parse(

208

'<div i18n="@@welcome">Hello {{name}}</div>',

209

'template.html',

210

true

211

);

212

213

if (parseResult.errors.length === 0) {

214

// Load existing translations

215

const translationBundle = TranslationBundle.load(

216

xliffTranslationContent,

217

'messages.xlf',

218

xliffDigest,

219

null,

220

xliffLoadToI18n,

221

MissingTranslationStrategy.Warning

222

);

223

224

// Merge translations with template

225

const mergedResult = parser.mergeTranslations(

226

parseResult.rootNodes,

227

translationBundle,

228

{ name: 'John' },

229

{ id: 'welcome' },

230

['div']

231

);

232

233

console.log('Merged content:', mergedResult.rootNodes);

234

}

235

```

236

237

### Multi-Format Bundle Export

238

239

```typescript

240

import { MessageBundle } from "@ngx-translate/i18n-polyfill/extractor";

241

import {

242

xliffWrite, xliffDigest,

243

xliff2Write, xliff2Digest,

244

xmbWrite, xmbDigest, xmbMapper

245

} from "@ngx-translate/i18n-polyfill/serializers";

246

247

const bundle = new MessageBundle("en");

248

249

// Add various message types

250

bundle.updateFromTemplate("Simple message", "app.ts");

251

bundle.updateFromTemplate("Hello {{user}}", "greeting.ts");

252

bundle.updateFromTemplate({

253

value: "Updated {count, plural, =0 {no items} =1 {one item} other {# items}}",

254

id: "item.count",

255

description: "Item count with pluralization"

256

}, "list.ts");

257

258

// Export to different formats

259

const xliffOutput = bundle.write(xliffWrite, xliffDigest);

260

const xliff2Output = bundle.write(xliff2Write, xliff2Digest);

261

const xmbOutput = bundle.write(xmbWrite, xmbDigest, undefined, xmbMapper);

262

263

// Save to files

264

require('fs').writeFileSync('messages.xlf', xliffOutput);

265

require('fs').writeFileSync('messages.xlf2', xliff2Output);

266

require('fs').writeFileSync('messages.xmb', xmbOutput);

267

```

268

269

### Translation Bundle Loading

270

271

```typescript

272

import { TranslationBundle } from "@ngx-translate/i18n-polyfill/parser";

273

import { xliffLoadToI18n, xliffDigest } from "@ngx-translate/i18n-polyfill/serializers";

274

275

// Load translation file content

276

const translationContent = require('fs').readFileSync('messages.fr.xlf', 'utf8');

277

278

// Create translation bundle

279

const bundle = TranslationBundle.load(

280

translationContent,

281

'messages.fr.xlf',

282

xliffDigest,

283

null, // No placeholder mapper needed

284

xliffLoadToI18n,

285

MissingTranslationStrategy.Warning

286

);

287

288

// Check for specific translations

289

const sourceMessage = createI18nMessage("Hello world");

290

if (bundle.has(sourceMessage)) {

291

const translation = bundle.get(sourceMessage);

292

console.log('Translation found:', translation);

293

} else {

294

console.log('Translation missing for:', sourceMessage);

295

}

296

```

297

298

## Message Processing Pipeline

299

300

The typical workflow for message bundle processing:

301

302

1. **Initialize Bundle**: Create MessageBundle with target locale

303

2. **Add Messages**: Use `updateFromTemplate()` to add messages from source code

304

3. **Process Templates**: Parse HTML templates if needed using HtmlParser

305

4. **Generate Output**: Use `write()` method with appropriate serializer

306

5. **Load Translations**: Use TranslationBundle to load existing translations

307

6. **Merge Content**: Combine source messages with translations

308

309

## Error Handling

310

311

The message bundle system provides comprehensive error handling:

312

313

- **Parse Errors**: HTML parsing errors are captured in ExtractionResult

314

- **Missing Translations**: Handled via MissingTranslationStrategy

315

- **Format Errors**: Invalid translation file formats throw descriptive errors

316

- **Template Errors**: Malformed templates and ICU expressions are reported with source locations