reneco-advanced-input-module 0.0.1-beta.2 → 0.0.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 (101) hide show
  1. package/dist/types/components/voice-input-module/voice-input-module.d.ts +4 -1
  2. package/dist/types/components.d.ts +4 -27
  3. package/dist/voice-input-module/index-Lt4F-TYq.js +4334 -0
  4. package/dist/voice-input-module/index-Lt4F-TYq.js.map +1 -0
  5. package/dist/voice-input-module/index.esm.js +12 -0
  6. package/dist/voice-input-module/index.esm.js.map +1 -1
  7. package/dist/voice-input-module/loader.esm.js.map +1 -1
  8. package/dist/voice-input-module/ocr-file-uploader.entry.esm.js.map +1 -0
  9. package/dist/{components/ocr-file-uploader2.js → voice-input-module/ocr-file-uploader.entry.js} +13 -28
  10. package/dist/voice-input-module/ocr-file-uploader.entry.js.map +1 -0
  11. package/dist/voice-input-module/voice-input-module.entry.esm.js.map +1 -0
  12. package/dist/voice-input-module/voice-input-module.entry.js +4467 -0
  13. package/dist/voice-input-module/voice-input-module.entry.js.map +1 -0
  14. package/dist/voice-input-module/voice-input-module.esm.js +49 -1
  15. package/dist/voice-input-module/voice-input-module.esm.js.map +1 -1
  16. package/package.json +2 -2
  17. package/www/build/index-Lt4F-TYq.js +4334 -0
  18. package/www/build/index-Lt4F-TYq.js.map +1 -0
  19. package/www/build/index.esm.js +12 -0
  20. package/www/build/index.esm.js.map +1 -1
  21. package/www/build/loader.esm.js.map +1 -1
  22. package/www/build/ocr-file-uploader.entry.esm.js.map +1 -0
  23. package/{dist/collection/components/ocr-file-uploader/ocr-file-uploader.js → www/build/ocr-file-uploader.entry.js} +18 -65
  24. package/www/build/ocr-file-uploader.entry.js.map +1 -0
  25. package/www/build/voice-input-module.entry.esm.js.map +1 -0
  26. package/www/build/voice-input-module.entry.js +4467 -0
  27. package/www/build/voice-input-module.entry.js.map +1 -0
  28. package/www/build/voice-input-module.esm.js +49 -1
  29. package/www/build/voice-input-module.esm.js.map +1 -1
  30. package/www/index.html +976 -227
  31. package/dist/cjs/app-globals-V2Kpy_OQ.js +0 -8
  32. package/dist/cjs/app-globals-V2Kpy_OQ.js.map +0 -1
  33. package/dist/cjs/index-BTSzTkSZ.js +0 -1494
  34. package/dist/cjs/index-BTSzTkSZ.js.map +0 -1
  35. package/dist/cjs/index.cjs.js +0 -5
  36. package/dist/cjs/index.cjs.js.map +0 -1
  37. package/dist/cjs/loader.cjs.js +0 -16
  38. package/dist/cjs/loader.cjs.js.map +0 -1
  39. package/dist/cjs/ocr-file-uploader.voice-input-module.entry.cjs.js.map +0 -1
  40. package/dist/cjs/ocr-file-uploader_2.cjs.entry.js +0 -1340
  41. package/dist/cjs/ocr-file-uploader_2.cjs.entry.js.map +0 -1
  42. package/dist/cjs/voice-input-module.cjs.js +0 -28
  43. package/dist/cjs/voice-input-module.cjs.js.map +0 -1
  44. package/dist/collection/collection-manifest.json +0 -13
  45. package/dist/collection/components/ocr-file-uploader/ocr-file-uploader.css +0 -26
  46. package/dist/collection/components/ocr-file-uploader/ocr-file-uploader.js.map +0 -1
  47. package/dist/collection/components/voice-input-module/voice-input-module.css +0 -286
  48. package/dist/collection/components/voice-input-module/voice-input-module.js +0 -897
  49. package/dist/collection/components/voice-input-module/voice-input-module.js.map +0 -1
  50. package/dist/collection/index.js +0 -12
  51. package/dist/collection/index.js.map +0 -1
  52. package/dist/collection/services/audio-recorder.service.js +0 -66
  53. package/dist/collection/services/audio-recorder.service.js.map +0 -1
  54. package/dist/collection/services/llm.service.js +0 -193
  55. package/dist/collection/services/llm.service.js.map +0 -1
  56. package/dist/collection/services/speech-to-text.service.js +0 -60
  57. package/dist/collection/services/speech-to-text.service.js.map +0 -1
  58. package/dist/collection/types/form-schema.types.js +0 -2
  59. package/dist/collection/types/form-schema.types.js.map +0 -1
  60. package/dist/collection/types/service-providers.types.js +0 -2
  61. package/dist/collection/types/service-providers.types.js.map +0 -1
  62. package/dist/collection/utils/schema-converter.js +0 -422
  63. package/dist/collection/utils/schema-converter.js.map +0 -1
  64. package/dist/components/index.js +0 -4
  65. package/dist/components/index.js.map +0 -1
  66. package/dist/components/ocr-file-uploader.d.ts +0 -11
  67. package/dist/components/ocr-file-uploader.js +0 -9
  68. package/dist/components/ocr-file-uploader.js.map +0 -1
  69. package/dist/components/ocr-file-uploader2.js.map +0 -1
  70. package/dist/components/voice-input-module.js +0 -1313
  71. package/dist/components/voice-input-module.js.map +0 -1
  72. package/dist/esm/app-globals-DQuL1Twl.js +0 -6
  73. package/dist/esm/app-globals-DQuL1Twl.js.map +0 -1
  74. package/dist/esm/index-jmc2yzBp.js +0 -1487
  75. package/dist/esm/index-jmc2yzBp.js.map +0 -1
  76. package/dist/esm/index.js +0 -4
  77. package/dist/esm/index.js.map +0 -1
  78. package/dist/esm/loader.js +0 -14
  79. package/dist/esm/loader.js.map +0 -1
  80. package/dist/esm/ocr-file-uploader.voice-input-module.entry.js.map +0 -1
  81. package/dist/esm/ocr-file-uploader_2.entry.js +0 -1337
  82. package/dist/esm/ocr-file-uploader_2.entry.js.map +0 -1
  83. package/dist/esm/voice-input-module.js +0 -24
  84. package/dist/esm/voice-input-module.js.map +0 -1
  85. package/dist/index.cjs.js +0 -1
  86. package/dist/index.js +0 -1
  87. package/dist/types/components/ocr-file-uploader/ocr-file-uploader.d.ts +0 -8
  88. package/dist/voice-input-module/ocr-file-uploader.voice-input-module.entry.esm.js.map +0 -1
  89. package/dist/voice-input-module/p-52e59129.entry.js +0 -2
  90. package/dist/voice-input-module/p-52e59129.entry.js.map +0 -1
  91. package/dist/voice-input-module/p-DQuL1Twl.js +0 -2
  92. package/dist/voice-input-module/p-DQuL1Twl.js.map +0 -1
  93. package/dist/voice-input-module/p-jmc2yzBp.js +0 -3
  94. package/dist/voice-input-module/p-jmc2yzBp.js.map +0 -1
  95. package/www/build/ocr-file-uploader.voice-input-module.entry.esm.js.map +0 -1
  96. package/www/build/p-52e59129.entry.js +0 -2
  97. package/www/build/p-52e59129.entry.js.map +0 -1
  98. package/www/build/p-DQuL1Twl.js +0 -2
  99. package/www/build/p-DQuL1Twl.js.map +0 -1
  100. package/www/build/p-jmc2yzBp.js +0 -3
  101. package/www/build/p-jmc2yzBp.js.map +0 -1
@@ -0,0 +1,4467 @@
1
+ import { r as registerInstance$1, a as createEvent, h as h$1 } from './index-Lt4F-TYq.js';
2
+
3
+ class AudioRecorderService {
4
+ constructor() {
5
+ this.mediaRecorder = null;
6
+ this.audioChunks = [];
7
+ this.stream = null;
8
+ }
9
+ async startRecording() {
10
+ try {
11
+ // Check if the API exists before calling
12
+ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
13
+ console.error('Failed to start recording:', 'Microphone access is not supported in this browser or the page is not served over HTTPS/localhost.');
14
+ return; // Exit gracefully instead of throwing
15
+ }
16
+ this.stream = await navigator.mediaDevices.getUserMedia({
17
+ audio: {
18
+ echoCancellation: true,
19
+ noiseSuppression: true,
20
+ autoGainControl: true
21
+ }
22
+ });
23
+ this.audioChunks = [];
24
+ this.mediaRecorder = new MediaRecorder(this.stream, {
25
+ mimeType: 'audio/webm;codecs=opus'
26
+ });
27
+ this.mediaRecorder.ondataavailable = (event) => {
28
+ if (event.data && event.data.size > 0) {
29
+ this.audioChunks.push(event.data);
30
+ }
31
+ };
32
+ this.mediaRecorder.start(100); // Collect data every 100ms
33
+ }
34
+ catch (error) {
35
+ console.error('Failed to start recording:', error);
36
+ }
37
+ }
38
+ async stopRecording() {
39
+ return new Promise((resolve, reject) => {
40
+ if (!this.mediaRecorder) {
41
+ reject(new Error('No active recording found'));
42
+ return;
43
+ }
44
+ this.mediaRecorder.onstop = () => {
45
+ const audioBlob = new Blob(this.audioChunks, { type: 'audio/webm' });
46
+ this.cleanup();
47
+ resolve(audioBlob);
48
+ };
49
+ this.mediaRecorder.onerror = (event) => {
50
+ reject(new Error(`Recording error: ${event}`));
51
+ };
52
+ this.mediaRecorder.stop();
53
+ });
54
+ }
55
+ isRecording() {
56
+ var _a;
57
+ return ((_a = this.mediaRecorder) === null || _a === void 0 ? void 0 : _a.state) === 'recording';
58
+ }
59
+ cleanup() {
60
+ if (this.stream) {
61
+ this.stream.getTracks().forEach(track => track.stop());
62
+ this.stream = null;
63
+ }
64
+ this.mediaRecorder = null;
65
+ this.audioChunks = [];
66
+ }
67
+ }
68
+
69
+ class WhisperSpeechToTextService {
70
+ constructor(config) {
71
+ // Get API key from config or environment
72
+ this.apiKey = (config === null || config === void 0 ? void 0 : config.apiKey) || this.getEnvironmentVariable('OPENAI_API_KEY') || '';
73
+ this.baseUrl = (config === null || config === void 0 ? void 0 : config.baseUrl) || 'https://api.openai.com/v1';
74
+ if (!this.apiKey) {
75
+ throw new Error('OpenAI API key is required for Whisper service');
76
+ }
77
+ }
78
+ getEnvironmentVariable(name) {
79
+ // In browser environment, we might get env vars through other means
80
+ if (typeof process !== 'undefined' && process.env) {
81
+ return process.env[name];
82
+ }
83
+ // Check if it's available as a global variable or through other means
84
+ return window[name] || undefined;
85
+ }
86
+ async transcribe(audioContent, lang = 'en') {
87
+ var _a;
88
+ try {
89
+ const formData = new FormData();
90
+ formData.append('file', audioContent);
91
+ formData.append('model', 'gpt-4o-transcribe'); // >>> tronque le texte ?
92
+ // formData.append('model', 'gpt-4o-mini-transcribe');// >>> tronque le texte ?
93
+ // formData.append('model', 'whisper-1');
94
+ formData.append('language', lang);
95
+ formData.append('response_format', 'json');
96
+ formData.append('max_output_tokens', '2000');
97
+ const response = await fetch(`${this.baseUrl}/audio/transcriptions`, {
98
+ method: 'POST',
99
+ headers: {
100
+ 'Authorization': `Bearer ${this.apiKey}`,
101
+ },
102
+ body: formData,
103
+ });
104
+ if (!response.ok) {
105
+ const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
106
+ throw new Error(`Transcription failed: ${((_a = errorData.error) === null || _a === void 0 ? void 0 : _a.message) || response.statusText}`);
107
+ }
108
+ const result = await response.json();
109
+ return result.text || '';
110
+ }
111
+ catch (error) {
112
+ throw new Error(`Speech-to-text transcription failed: ${error.message}`);
113
+ }
114
+ }
115
+ }
116
+ class SpeechToTextServiceFactory {
117
+ static create(config) {
118
+ var _a;
119
+ const provider = ((_a = config.speechToText) === null || _a === void 0 ? void 0 : _a.provider) || 'whisper';
120
+ switch (provider) {
121
+ case 'whisper':
122
+ return new WhisperSpeechToTextService(config.speechToText);
123
+ default:
124
+ throw new Error(`Unsupported speech-to-text provider: ${provider}`);
125
+ }
126
+ }
127
+ }
128
+
129
+ class OpenAILLMService {
130
+ constructor(config) {
131
+ // Get API key from config or environment
132
+ this.apiKey = (config === null || config === void 0 ? void 0 : config.apiKey) || this.getEnvironmentVariable('OPENAI_API_KEY') || '';
133
+ // the newest OpenAI model is "gpt-4.1-mini". do not change this unless explicitly requested by the user
134
+ // this.model = config?.model || 'gpt-4.1-mini';
135
+ this.model = (config === null || config === void 0 ? void 0 : config.model) || 'gpt-4.1';
136
+ this.baseUrl = (config === null || config === void 0 ? void 0 : config.baseUrl) || 'https://api.openai.com/v1';
137
+ if (!this.apiKey) {
138
+ throw new Error('OpenAI API key is required for LLM service');
139
+ }
140
+ }
141
+ getEnvironmentVariable(name) {
142
+ // In browser environment, we might get env vars through other means
143
+ if (typeof process !== 'undefined' && process.env) {
144
+ return process.env[name];
145
+ }
146
+ // Check if it's available as a global variable or through other means
147
+ return window[name] || undefined;
148
+ }
149
+ getOptimizeFieldsDescription(schema) {
150
+ return Object.values(schema).map((field) => {
151
+ var _a;
152
+ return `- ${(_a = field.name) !== null && _a !== void 0 ? _a : field.title} ` +
153
+ `(${field.type}` +
154
+ `${field.required ? ', required' : ''}` +
155
+ `${field.readonly ? ', readonly' : ''}` +
156
+ `${field.min && field.min !== "" ? ', min=' + field.min : ''}` +
157
+ `${field.max && field.max !== "" ? ', max=' + field.max : ''}` +
158
+ `)` +
159
+ `${field.options ? ` - options: ${field.options.join(', ')}` : ''}`;
160
+ }).join('\n');
161
+ }
162
+ async fillFormFromTranscription(transcription, schema) {
163
+ return this.fillForm(transcription, schema, true);
164
+ }
165
+ async fillFormFromJson(json, schema) {
166
+ return this.fillForm(json, schema, false);
167
+ }
168
+ async fillForm(data, schema, dataIsTranscription = true) {
169
+ var _a, _b;
170
+ try {
171
+ // Handle complex schema format with fields array
172
+ if ((schema === null || schema === void 0 ? void 0 : schema.fields) || (schema === null || schema === void 0 ? void 0 : schema.schema)) {
173
+ const finalSchema = (schema === null || schema === void 0 ? void 0 : schema.fields) || (schema === null || schema === void 0 ? void 0 : schema.schema);
174
+ const systemPrompt = `You are an expert form-filling assistant. You will receive a voice transcription and form field definitions. Your task is to extract values from the spoken content.
175
+ Rules:
176
+ 1. Only extract values that can be confidently determined from the transcription
177
+ 2. Respect field types (string, number, datetime, boolean, select)
178
+ 3. For datetime fields, use ISO format (YYYY-MM-DDTHH:MM)
179
+ 4. For date fields, use the following format: DD/MM/YYYY
180
+ 5. For boolean fields, interpret yes/no, true/false, positive/negative responses
181
+ 6. For select fields, use exact option values from the provided choices
182
+ 7. Only include fields where relevant information is found
183
+ 8. The current GMT datetime is ${new Date().toGMTString()}
184
+ 9. Respect the constraints written between parenthesis for readonly status (readonly fields must not be filled with values), min and max values, whatever the transcription says
185
+
186
+ Respond with JSON in this exact format: {"fields": [{"name": "field_name", "value": "extracted_value"}]}`;
187
+ let userPrompt = `
188
+ Voice transcription: "${data}"
189
+
190
+ Form fields:
191
+ ${this.getOptimizeFieldsDescription(finalSchema)}
192
+
193
+ Please extract values from the Transcription for these fields.
194
+ `;
195
+ //TODO
196
+ // const userPrompt = (
197
+ // dataIsTranscription
198
+ // ?
199
+ // `Voice transcription: "${data}"`
200
+ // :
201
+ // `Json datas: "${JSON.stringify(data)}"`
202
+ // )+`
203
+ // Form fields:
204
+ // ${this.getOptimizeFieldsDescription(finalSchema)}
205
+ // Please extract values from the ` +
206
+ // (
207
+ // dataIsTranscription
208
+ // ?
209
+ // `Transcription`
210
+ // :
211
+ // `Json generated file`
212
+ // )+` for these fields.`;
213
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
214
+ method: 'POST',
215
+ headers: {
216
+ 'Content-Type': 'application/json',
217
+ 'Authorization': `Bearer ${this.apiKey}`,
218
+ },
219
+ body: JSON.stringify({
220
+ model: this.model,
221
+ messages: [
222
+ { role: 'system', content: systemPrompt },
223
+ { role: 'user', content: userPrompt }
224
+ ],
225
+ response_format: { type: 'json_object' },
226
+ temperature: 0.1,
227
+ }),
228
+ });
229
+ if (!response.ok) {
230
+ const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
231
+ throw new Error(`LLM API failed: ${((_a = errorData.error) === null || _a === void 0 ? void 0 : _a.message) || response.statusText}`);
232
+ }
233
+ const result = await response.json();
234
+ return JSON.parse(result.choices[0].message.content);
235
+ }
236
+ // Handle simple schema format (backward compatibility)
237
+ const systemPrompt = `You are an expert form-filling assistant. You will receive a voice transcription and a JSON form schema. Your task is to intelligently fill the form fields based on the spoken content.
238
+ Rules:
239
+ 1. Only fill fields that can be confidently determined from the transcription
240
+ 2. Respect field types (string, number, date, boolean, select)
241
+ 3. For datetime fields, use ISO format (YYYY-MM-DDTHH:MM)
242
+ 4. For date fields, use the following format: DD/MM/YYYY
243
+ 5. For boolean fields, interpret yes/no, true/false, positive/negative responses
244
+ 6. For select fields, match the closest option from the provided choices
245
+ 7. Leave fields empty if no relevant information is found
246
+ 8. Return the same schema structure with 'default' values filled
247
+ 9. The current GMT datetime is ${new Date().toGMTString()}
248
+ 10. Respect the constraints written between parenthesis for readonly status (readonly fields must not be filled with values), min and max values, whatever the transcription says
249
+
250
+ Respond with JSON in this exact format: {"schema": {...}}`;
251
+ let userPrompt = `
252
+ Voice transcription: "${data}"
253
+
254
+ Form schema to fill:
255
+ ${JSON.stringify(schema, null, 2)}
256
+
257
+ Please fill the form fields based on the Transcription and return the schema with default values populated.
258
+ `;
259
+ // const userPrompt = (
260
+ // dataIsTranscription
261
+ // ?
262
+ // `Voice transcription: "${data}"`
263
+ // :
264
+ // `Json datas: "${JSON.stringify(data)}"`
265
+ // )+`
266
+ // Form schema to fill:
267
+ // ${JSON.stringify(schema, null, 2)}
268
+ // Please fill the form fields based on the ` +
269
+ // (
270
+ // dataIsTranscription
271
+ // ?
272
+ // `Transcription`
273
+ // :
274
+ // `Json generated file`
275
+ // )+` nd return the schema with default values populated.`;
276
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
277
+ method: 'POST',
278
+ headers: {
279
+ 'Content-Type': 'application/json',
280
+ 'Authorization': `Bearer ${this.apiKey}`,
281
+ },
282
+ body: JSON.stringify({
283
+ model: this.model,
284
+ messages: [
285
+ { role: 'system', content: systemPrompt },
286
+ { role: 'user', content: userPrompt }
287
+ ],
288
+ response_format: { type: 'json_object' },
289
+ temperature: 0.1, // Low temperature for consistency
290
+ }),
291
+ });
292
+ if (!response.ok) {
293
+ const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
294
+ throw new Error(`LLM API failed: ${((_b = errorData.error) === null || _b === void 0 ? void 0 : _b.message) || response.statusText}`);
295
+ }
296
+ const result = await response.json();
297
+ const filledSchema = JSON.parse(result.choices[0].message.content);
298
+ // Validate that the response has the correct structure
299
+ if (!filledSchema.schema) {
300
+ throw new Error('Invalid response format from LLM service');
301
+ }
302
+ return filledSchema;
303
+ }
304
+ catch (error) {
305
+ throw new Error(`Form filling failed: ${error.message}`);
306
+ }
307
+ }
308
+ }
309
+ class LLMServiceFactory {
310
+ static create(config) {
311
+ var _a;
312
+ const provider = ((_a = config.llm) === null || _a === void 0 ? void 0 : _a.provider) || 'openai';
313
+ switch (provider) {
314
+ case 'openai':
315
+ return new OpenAILLMService(config.llm);
316
+ default:
317
+ throw new Error(`Unsupported LLM provider: ${provider}`);
318
+ }
319
+ }
320
+ }
321
+
322
+ class SchemaConverter {
323
+ /**
324
+ * Convert XML form definition to JSON schema
325
+ */
326
+ static convertXmlToJsonLegacy(xmlForm) {
327
+ try {
328
+ const parser = new DOMParser();
329
+ const xmlDoc = parser.parseFromString(xmlForm, 'text/xml');
330
+ if (xmlDoc.querySelector('parsererror')) {
331
+ throw new Error('Invalid XML format');
332
+ }
333
+ const schema = {
334
+ schema: {}
335
+ };
336
+ // Extract form title and description
337
+ const formElement = xmlDoc.querySelector('form');
338
+ if (formElement) {
339
+ schema.title = formElement.getAttribute('title') || undefined;
340
+ schema.description = formElement.getAttribute('description') || undefined;
341
+ }
342
+ // Process input fields
343
+ const inputs = xmlDoc.querySelectorAll('input, select, textarea');
344
+ inputs.forEach(input => {
345
+ const name = input.getAttribute('name');
346
+ if (!name)
347
+ return;
348
+ const field = {
349
+ type: this.mapXmlTypeToJsonTypeLegacy(input.tagName.toLowerCase(), input.getAttribute('type')),
350
+ title: input.getAttribute('title') || input.getAttribute('placeholder') || name,
351
+ description: input.getAttribute('description') || undefined,
352
+ required: input.hasAttribute('required'),
353
+ default: input.getAttribute('value') || undefined
354
+ };
355
+ // Handle select options
356
+ if (input.tagName.toLowerCase() === 'select') {
357
+ const options = Array.from(input.querySelectorAll('option')).map(option => option.textContent || option.getAttribute('value') || '');
358
+ if (options.length > 0) {
359
+ field.options = options;
360
+ }
361
+ }
362
+ // Handle validation attributes
363
+ const min = input.getAttribute('min');
364
+ const max = input.getAttribute('max');
365
+ const pattern = input.getAttribute('pattern');
366
+ if (min)
367
+ field.min = parseFloat(min);
368
+ if (max)
369
+ field.max = parseFloat(max);
370
+ if (pattern)
371
+ field.pattern = pattern;
372
+ schema.schema[name] = field;
373
+ });
374
+ return schema;
375
+ }
376
+ catch (error) {
377
+ throw new Error(`XML to JSON conversion failed: ${error.message}`);
378
+ }
379
+ }
380
+ /**
381
+ * Convert JSON schema to XML form definition
382
+ */
383
+ static convertJsonToXmlLegacy(jsonForm) {
384
+ try {
385
+ const doc = document.implementation.createDocument('', '', null);
386
+ const form = doc.createElement('form');
387
+ if (jsonForm.title) {
388
+ form.setAttribute('title', jsonForm.title);
389
+ }
390
+ if (jsonForm.description) {
391
+ form.setAttribute('description', jsonForm.description);
392
+ }
393
+ Object.entries(jsonForm.schema).forEach(([fieldName, field]) => {
394
+ var _a;
395
+ // Inject default value from root if present
396
+ const valueFromRoot = jsonForm[fieldName];
397
+ const fieldWithDefault = Object.assign(Object.assign({}, field), { default: (_a = field.default) !== null && _a !== void 0 ? _a : valueFromRoot // field.default has priority
398
+ });
399
+ const element = this.createXmlElementLegacy(doc, fieldName, fieldWithDefault);
400
+ if (element) {
401
+ form.appendChild(element);
402
+ }
403
+ });
404
+ doc.appendChild(form);
405
+ const serializer = new XMLSerializer();
406
+ return serializer.serializeToString(doc);
407
+ }
408
+ catch (error) {
409
+ throw new Error(`JSON to XML conversion failed: ${error.message}`);
410
+ }
411
+ }
412
+ static mapXmlTypeToJsonTypeLegacy(tagName, type) {
413
+ switch (tagName) {
414
+ case 'select':
415
+ return 'select';
416
+ case 'textarea':
417
+ return 'string';
418
+ case 'input':
419
+ switch (type) {
420
+ case 'number':
421
+ case 'range':
422
+ return 'number';
423
+ case 'date':
424
+ case 'datetime-local':
425
+ case 'time':
426
+ return 'date';
427
+ case 'checkbox':
428
+ return 'boolean';
429
+ default:
430
+ return 'string';
431
+ }
432
+ default:
433
+ return 'string';
434
+ }
435
+ }
436
+ static createXmlElementLegacy(doc, fieldName, field) {
437
+ let element;
438
+ switch (field.type) {
439
+ case 'select':
440
+ element = doc.createElement('select');
441
+ if (field.options) {
442
+ field.options.forEach(option => {
443
+ const optionElement = doc.createElement('option');
444
+ optionElement.setAttribute('value', option);
445
+ optionElement.textContent = option;
446
+ // Set selected if it matches the default value
447
+ if (field.default !== undefined && field.default === option) {
448
+ optionElement.setAttribute('selected', 'true');
449
+ }
450
+ element.appendChild(optionElement);
451
+ });
452
+ }
453
+ break;
454
+ case 'boolean':
455
+ element = doc.createElement('input');
456
+ element.setAttribute('type', 'checkbox');
457
+ if (field.default === true || field.default === 'true') {
458
+ element.setAttribute('checked', 'true');
459
+ }
460
+ break;
461
+ case 'number':
462
+ element = doc.createElement('input');
463
+ element.setAttribute('type', 'number');
464
+ if (field.min !== undefined)
465
+ element.setAttribute('min', field.min.toString());
466
+ if (field.max !== undefined)
467
+ element.setAttribute('max', field.max.toString());
468
+ if (field.default !== undefined)
469
+ element.setAttribute('value', field.default.toString());
470
+ break;
471
+ case 'date':
472
+ element = doc.createElement('input');
473
+ element.setAttribute('type', 'date');
474
+ if (field.default !== undefined)
475
+ element.setAttribute('value', field.default.toString());
476
+ break;
477
+ default: // string, text, etc.
478
+ element = doc.createElement('input');
479
+ element.setAttribute('type', 'text');
480
+ if (field.default !== undefined)
481
+ element.setAttribute('value', field.default.toString());
482
+ }
483
+ element.setAttribute('name', fieldName);
484
+ element.setAttribute('title', field.title);
485
+ if (field.description) {
486
+ element.setAttribute('description', field.description);
487
+ }
488
+ if (field.required) {
489
+ element.setAttribute('required', 'true');
490
+ }
491
+ if (field.pattern) {
492
+ element.setAttribute('pattern', field.pattern);
493
+ }
494
+ return element;
495
+ }
496
+ /**
497
+ * Convert new XML form definition to JSON schema
498
+ */
499
+ static async convertXmlToJson(xmlForm, classificationRootURL = "http://localhost", lang = 'en') {
500
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
501
+ try {
502
+ const parser = new DOMParser();
503
+ const xmlDoc = parser.parseFromString(xmlForm, 'text/xml');
504
+ if (xmlDoc.querySelector('parsererror')) {
505
+ throw new Error('Invalid XML format');
506
+ }
507
+ // Root Xforms element (optional)
508
+ const xforms = xmlDoc.querySelector('Xforms');
509
+ if (!xforms)
510
+ throw new Error('No Xforms root element found');
511
+ const fields = xforms.querySelectorAll('Fields');
512
+ if (fields.length === 0)
513
+ throw new Error('No Fields elements found');
514
+ const schema = {
515
+ fields: {}
516
+ };
517
+ for (const fieldEl of Array.from(fields)) {
518
+ // Read key info
519
+ const name = (_b = (_a = fieldEl.querySelector('SystemName')) === null || _a === void 0 ? void 0 : _a.textContent) === null || _b === void 0 ? void 0 : _b.trim();
520
+ if (!name)
521
+ return;
522
+ const helpText = (_d = (_c = fieldEl.querySelector('HelpText')) === null || _c === void 0 ? void 0 : _c.textContent) === null || _d === void 0 ? void 0 : _d.trim();
523
+ const defaultValue = (_e = fieldEl.querySelector('DefaultValue')) === null || _e === void 0 ? void 0 : _e.textContent;
524
+ const enabledText = ((_g = (_f = fieldEl.querySelector('Enabled')) === null || _f === void 0 ? void 0 : _f.textContent) === null || _g === void 0 ? void 0 : _g.trim().toLowerCase()) || 'true';
525
+ const isEnabled = enabledText === 'true';
526
+ // keep as memory
527
+ const field_ID = (_h = fieldEl.querySelector('ID')) === null || _h === void 0 ? void 0 : _h.textContent;
528
+ const field_TFie_PK_ID = (_j = fieldEl.querySelector('TFie_PK_ID')) === null || _j === void 0 ? void 0 : _j.textContent;
529
+ const field_TVal_PK_ID = (_k = fieldEl.querySelector('TVal_PK_ID')) === null || _k === void 0 ? void 0 : _k.textContent;
530
+ const field_TFIn_PK_ID = (_l = fieldEl.querySelector('TFIn_PK_ID')) === null || _l === void 0 ? void 0 : _l.textContent;
531
+ const field_isForm = (_m = fieldEl.querySelector('isForm')) === null || _m === void 0 ? void 0 : _m.textContent;
532
+ const field_LabelText = (_o = fieldEl.querySelector('LabelText')) === null || _o === void 0 ? void 0 : _o.textContent;
533
+ const field_SystemName = (_p = fieldEl.querySelector('SystemName')) === null || _p === void 0 ? void 0 : _p.textContent;
534
+ const field_CssStyle = (_q = fieldEl.querySelector('CssStyle')) === null || _q === void 0 ? void 0 : _q.textContent;
535
+ const field_ControlType = ((_r = fieldEl.querySelector('ControlType')) === null || _r === void 0 ? void 0 : _r.textContent) || 'TextBox';
536
+ const field_ValidationRequired = (_s = fieldEl.querySelector('ValidationRequired')) === null || _s === void 0 ? void 0 : _s.textContent;
537
+ const field_ValidationMin = (_t = fieldEl.querySelector('ValidationMin')) === null || _t === void 0 ? void 0 : _t.textContent;
538
+ const field_ValidationMax = (_u = fieldEl.querySelector('ValidationMax')) === null || _u === void 0 ? void 0 : _u.textContent;
539
+ const field_Mask = (_v = fieldEl.querySelector('Mask')) === null || _v === void 0 ? void 0 : _v.textContent;
540
+ const field_TypeId = (_w = fieldEl.querySelector('TypeId')) === null || _w === void 0 ? void 0 : _w.textContent;
541
+ const field_Unit = (_x = fieldEl.querySelector('Unit')) === null || _x === void 0 ? void 0 : _x.textContent;
542
+ const field_TFie_Fullpath = (_y = fieldEl.querySelector('TFie_Fullpath')) === null || _y === void 0 ? void 0 : _y.textContent;
543
+ const field_TVal_FK_Parent_ID = (_z = fieldEl.querySelector('TVal_FK_Parent_ID')) === null || _z === void 0 ? void 0 : _z.textContent;
544
+ const field = {
545
+ type: this.mapControlTypeToJsonType(field_ControlType),
546
+ title: field_LabelText,
547
+ description: helpText,
548
+ required: (field_ValidationRequired === null || field_ValidationRequired === void 0 ? void 0 : field_ValidationRequired.toLowerCase()) === 'required',
549
+ default: defaultValue || undefined,
550
+ realType: field_ControlType,
551
+ Enabled: isEnabled,
552
+ ID: field_ID,
553
+ TFie_PK_ID: field_TFie_PK_ID,
554
+ TVal_PK_ID: field_TVal_PK_ID,
555
+ TFIn_PK_ID: field_TFIn_PK_ID,
556
+ isForm: field_isForm,
557
+ LabelText: field_LabelText,
558
+ SystemName: field_SystemName,
559
+ CssStyle: field_CssStyle,
560
+ ControlType: field_ControlType,
561
+ ValidationRequired: field_ValidationRequired,
562
+ ValidationMin: field_ValidationMin,
563
+ ValidationMax: field_ValidationMax,
564
+ Mask: field_Mask,
565
+ TypeId: field_TypeId,
566
+ Unit: field_Unit,
567
+ TFie_Fullpath: field_TFie_Fullpath,
568
+ TVal_FK_Parent_ID: field_TVal_FK_Parent_ID
569
+ };
570
+ // Handle select options
571
+ if (field.type.toLowerCase() === 'select') {
572
+ try {
573
+ const response = await fetch(`${classificationRootURL}/ng/api/v1/classification/getList/${field.ControlType.toLowerCase() == 'termpicker' ? "Position" : "Thesaurus"}/?StartNodeID=${field_TypeId}`);
574
+ if (!response.ok)
575
+ throw new Error(`HTTP error! status: ${response.status}`);
576
+ const data = await response.json();
577
+ if (Array.isArray(data)) {
578
+ const options = data.map(item => ({
579
+ value: item.ID,
580
+ label: item.System_Name
581
+ }));
582
+ if (options.length > 0) {
583
+ field.pickerOptions = options;
584
+ // TODO on degage les quotes simples temporairement, a corriger
585
+ field.options = options.map(option => option.label.replace("'", ""));
586
+ }
587
+ }
588
+ else {
589
+ console.error("Unexpected API response format:", data);
590
+ }
591
+ }
592
+ catch (error) {
593
+ console.error("Error fetching classification data:", error);
594
+ }
595
+ }
596
+ if (field_ValidationMin)
597
+ field.min = parseFloat(field_ValidationMin);
598
+ if (field_ValidationMax)
599
+ field.max = parseFloat(field_ValidationMax);
600
+ if (field_Mask)
601
+ field.pattern = field_Mask;
602
+ // Optional: Add any other fields you want to track, e.g. min, max, pattern (not clearly in your XML)
603
+ // You could also add the raw ControlType for round-trip fidelity if you want
604
+ schema.fields[field_ID] = field;
605
+ }
606
+ ;
607
+ return schema;
608
+ }
609
+ catch (error) {
610
+ throw new Error(`XML to JSON conversion failed: ${error.message}`);
611
+ }
612
+ }
613
+ /**
614
+ * Convert JSON schema back to your new XML form definition format
615
+ */
616
+ static convertJsonToXml(jsonForm) {
617
+ try {
618
+ const doc = document.implementation.createDocument('', '', null);
619
+ const xforms = doc.createElement('Xforms');
620
+ Object.entries((jsonForm.schema ? jsonForm.schema : jsonForm.fields)).forEach(([fieldID, field]) => {
621
+ const fieldEl = doc.createElement('Fields');
622
+ const fieldToUse = field;
623
+ // Set all subelements based on your XML structure
624
+ // ID, PK IDs etc are missing here, so omit or generate dummy
625
+ // <SystemName>
626
+ const systemNameEl = doc.createElement('SystemName');
627
+ systemNameEl.textContent = fieldToUse.SystemName;
628
+ fieldEl.appendChild(systemNameEl);
629
+ // <LabelText>
630
+ const labelEl = doc.createElement('LabelText');
631
+ labelEl.textContent = fieldToUse.title || fieldID;
632
+ fieldEl.appendChild(labelEl);
633
+ // <HelpText>
634
+ const helpEl = doc.createElement('HelpText');
635
+ helpEl.textContent = fieldToUse.description;
636
+ fieldEl.appendChild(helpEl);
637
+ // <ControlType>
638
+ const controlTypeEl = doc.createElement('ControlType');
639
+ controlTypeEl.textContent = fieldToUse.realType;
640
+ fieldEl.appendChild(controlTypeEl);
641
+ // <ValidationRequired>
642
+ const validationEl = doc.createElement('ValidationRequired');
643
+ validationEl.textContent = fieldToUse.required ? 'Required' : 'Not Required';
644
+ fieldEl.appendChild(validationEl);
645
+ // <DefaultValue>
646
+ const defaultEl = doc.createElement('DefaultValue');
647
+ const valueEl = doc.createElement('Value');
648
+ if (jsonForm[fieldID] !== undefined) {
649
+ defaultEl.textContent = jsonForm[fieldID].toString();
650
+ valueEl.textContent = jsonForm[fieldID].toString();
651
+ }
652
+ else {
653
+ defaultEl.textContent = fieldToUse.default || fieldToUse.value;
654
+ valueEl.textContent = fieldToUse.value || fieldToUse.default;
655
+ }
656
+ fieldEl.appendChild(defaultEl);
657
+ fieldEl.appendChild(valueEl);
658
+ // <Enabled>
659
+ const enabledEl = doc.createElement('Enabled');
660
+ enabledEl.textContent = fieldToUse.Enabled === false ? 'False' : 'True';
661
+ fieldEl.appendChild(enabledEl);
662
+ // Add <isForm> Field to distinguish Field or Header etc
663
+ const isFormEl = doc.createElement('isForm');
664
+ isFormEl.textContent = fieldToUse.isForm;
665
+ fieldEl.appendChild(isFormEl);
666
+ if (fieldToUse.type === 'header') {
667
+ const headerEl = doc.createElement('Header');
668
+ headerEl.textContent = fieldToUse.title;
669
+ fieldEl.appendChild(headerEl);
670
+ }
671
+ const idEl = doc.createElement('ID');
672
+ idEl.textContent = fieldToUse.ID;
673
+ fieldEl.appendChild(idEl);
674
+ const tfiePkIdEl = doc.createElement('TFie_PK_ID');
675
+ tfiePkIdEl.textContent = fieldToUse.TFie_PK_ID;
676
+ fieldEl.appendChild(tfiePkIdEl);
677
+ const tvalPkIdEl = doc.createElement('TVal_PK_ID');
678
+ tvalPkIdEl.textContent = fieldToUse.TVal_PK_ID;
679
+ fieldEl.appendChild(tvalPkIdEl);
680
+ const tfInPkIdEl = doc.createElement('TFIn_PK_ID');
681
+ tfInPkIdEl.textContent = fieldToUse.TFIn_PK_ID;
682
+ fieldEl.appendChild(tfInPkIdEl);
683
+ const cssStyleEl = doc.createElement('CssStyle');
684
+ cssStyleEl.textContent = fieldToUse.CssStyle;
685
+ fieldEl.appendChild(cssStyleEl);
686
+ const typeIdEl = doc.createElement('TypeId');
687
+ typeIdEl.textContent = fieldToUse.TypeId;
688
+ fieldEl.appendChild(typeIdEl);
689
+ const unitEl = doc.createElement('Unit');
690
+ unitEl.textContent = fieldToUse.Unit;
691
+ fieldEl.appendChild(unitEl);
692
+ const tfieFullPathEl = doc.createElement('TFie_Fullpath');
693
+ tfieFullPathEl.textContent = fieldToUse.TFie_Fullpath;
694
+ fieldEl.appendChild(tfieFullPathEl);
695
+ const tvalFkParentIdEl = doc.createElement('TVal_FK_Parent_ID');
696
+ tvalFkParentIdEl.textContent = fieldToUse.TVal_FK_Parent_ID;
697
+ fieldEl.appendChild(tvalFkParentIdEl);
698
+ const validationMinEl = doc.createElement('ValidationMin');
699
+ validationMinEl.textContent = fieldToUse.ValidationMin;
700
+ fieldEl.appendChild(validationMinEl);
701
+ const validationMaxEl = doc.createElement('ValidationMax');
702
+ validationMaxEl.textContent = fieldToUse.ValidationMax;
703
+ fieldEl.appendChild(validationMaxEl);
704
+ const maskEl = doc.createElement('Mask');
705
+ maskEl.textContent = fieldToUse.Mask;
706
+ fieldEl.appendChild(maskEl);
707
+ // Append to Xforms root
708
+ xforms.appendChild(fieldEl);
709
+ });
710
+ doc.appendChild(xforms);
711
+ const serializer = new XMLSerializer();
712
+ return serializer.serializeToString(doc);
713
+ }
714
+ catch (error) {
715
+ throw new Error(`JSON to XML conversion failed: ${error.message}`);
716
+ }
717
+ }
718
+ static mapControlTypeToJsonType(controlType) {
719
+ // Map your ControlType XML field to JSON field types
720
+ switch (controlType.toLowerCase()) {
721
+ case 'textbox':
722
+ case 'text':
723
+ return 'string';
724
+ case 'datepicker':
725
+ return 'date';
726
+ case 'thesauruspicker':
727
+ case 'thesauruspicker-ddl':
728
+ case 'termpicker':
729
+ return 'select';
730
+ case 'dbpicker':
731
+ return 'dbpicker'; // custom type if needed
732
+ case 'header':
733
+ return 'header'; // special type to handle header elements
734
+ case 'checkbox':
735
+ return 'boolean';
736
+ case 'realpicker':
737
+ return 'number';
738
+ default:
739
+ return 'string';
740
+ }
741
+ }
742
+ }
743
+
744
+ const NAMESPACE = 'ocr-file-uploader';
745
+ const BUILD = /* ocr-file-uploader */ { hotModuleReplacement: false, hydratedSelectorName: "hydrated", lazyLoad: true, prop: true, propChangeCallback: false, updatable: true};
746
+
747
+ /*
748
+ Stencil Client Platform v4.40.1 | MIT Licensed | https://stenciljs.com
749
+ */
750
+ var __create = Object.create;
751
+ var __defProp = Object.defineProperty;
752
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
753
+ var __getOwnPropNames = Object.getOwnPropertyNames;
754
+ var __getProtoOf = Object.getPrototypeOf;
755
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
756
+ var __typeError = (msg) => {
757
+ throw TypeError(msg);
758
+ };
759
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
760
+ var __commonJS = (cb, mod) => function __require() {
761
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
762
+ };
763
+ var __export = (target, all) => {
764
+ for (var name in all)
765
+ __defProp(target, name, { get: all[name], enumerable: true });
766
+ };
767
+ var __copyProps = (to, from, except, desc) => {
768
+ if (from && typeof from === "object" || typeof from === "function") {
769
+ for (let key of __getOwnPropNames(from))
770
+ if (!__hasOwnProp.call(to, key) && key !== except)
771
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
772
+ }
773
+ return to;
774
+ };
775
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
776
+ // If the importer is in node compatibility mode or this is not an ESM
777
+ // file that has been converted to a CommonJS file using a Babel-
778
+ // compatible transform (i.e. "__esModule" has not been set), then set
779
+ // "default" to the CommonJS "module.exports" for node compatibility.
780
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
781
+ mod
782
+ ));
783
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
784
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
785
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
786
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
787
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
788
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
789
+
790
+ // node_modules/balanced-match/index.js
791
+ var require_balanced_match = __commonJS({
792
+ "node_modules/balanced-match/index.js"(exports, module) {
793
+ module.exports = balanced;
794
+ function balanced(a, b, str) {
795
+ if (a instanceof RegExp) a = maybeMatch(a, str);
796
+ if (b instanceof RegExp) b = maybeMatch(b, str);
797
+ var r = range(a, b, str);
798
+ return r && {
799
+ start: r[0],
800
+ end: r[1],
801
+ pre: str.slice(0, r[0]),
802
+ body: str.slice(r[0] + a.length, r[1]),
803
+ post: str.slice(r[1] + b.length)
804
+ };
805
+ }
806
+ function maybeMatch(reg, str) {
807
+ var m = str.match(reg);
808
+ return m ? m[0] : null;
809
+ }
810
+ balanced.range = range;
811
+ function range(a, b, str) {
812
+ var begs, beg, left, right, result;
813
+ var ai = str.indexOf(a);
814
+ var bi = str.indexOf(b, ai + 1);
815
+ var i2 = ai;
816
+ if (ai >= 0 && bi > 0) {
817
+ if (a === b) {
818
+ return [ai, bi];
819
+ }
820
+ begs = [];
821
+ left = str.length;
822
+ while (i2 >= 0 && !result) {
823
+ if (i2 == ai) {
824
+ begs.push(i2);
825
+ ai = str.indexOf(a, i2 + 1);
826
+ } else if (begs.length == 1) {
827
+ result = [begs.pop(), bi];
828
+ } else {
829
+ beg = begs.pop();
830
+ if (beg < left) {
831
+ left = beg;
832
+ right = bi;
833
+ }
834
+ bi = str.indexOf(b, i2 + 1);
835
+ }
836
+ i2 = ai < bi && ai >= 0 ? ai : bi;
837
+ }
838
+ if (begs.length) {
839
+ result = [left, right];
840
+ }
841
+ }
842
+ return result;
843
+ }
844
+ }
845
+ });
846
+
847
+ // node_modules/brace-expansion/index.js
848
+ var require_brace_expansion = __commonJS({
849
+ "node_modules/brace-expansion/index.js"(exports, module) {
850
+ var balanced = require_balanced_match();
851
+ module.exports = expandTop;
852
+ var escSlash = "\0SLASH" + Math.random() + "\0";
853
+ var escOpen = "\0OPEN" + Math.random() + "\0";
854
+ var escClose = "\0CLOSE" + Math.random() + "\0";
855
+ var escComma = "\0COMMA" + Math.random() + "\0";
856
+ var escPeriod = "\0PERIOD" + Math.random() + "\0";
857
+ function numeric(str) {
858
+ return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
859
+ }
860
+ function escapeBraces(str) {
861
+ return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
862
+ }
863
+ function unescapeBraces(str) {
864
+ return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
865
+ }
866
+ function parseCommaParts(str) {
867
+ if (!str)
868
+ return [""];
869
+ var parts = [];
870
+ var m = balanced("{", "}", str);
871
+ if (!m)
872
+ return str.split(",");
873
+ var pre = m.pre;
874
+ var body = m.body;
875
+ var post = m.post;
876
+ var p = pre.split(",");
877
+ p[p.length - 1] += "{" + body + "}";
878
+ var postParts = parseCommaParts(post);
879
+ if (post.length) {
880
+ p[p.length - 1] += postParts.shift();
881
+ p.push.apply(p, postParts);
882
+ }
883
+ parts.push.apply(parts, p);
884
+ return parts;
885
+ }
886
+ function expandTop(str) {
887
+ if (!str)
888
+ return [];
889
+ if (str.substr(0, 2) === "{}") {
890
+ str = "\\{\\}" + str.substr(2);
891
+ }
892
+ return expand2(escapeBraces(str), true).map(unescapeBraces);
893
+ }
894
+ function embrace(str) {
895
+ return "{" + str + "}";
896
+ }
897
+ function isPadded(el) {
898
+ return /^-?0\d/.test(el);
899
+ }
900
+ function lte(i2, y) {
901
+ return i2 <= y;
902
+ }
903
+ function gte(i2, y) {
904
+ return i2 >= y;
905
+ }
906
+ function expand2(str, isTop) {
907
+ var expansions = [];
908
+ var m = balanced("{", "}", str);
909
+ if (!m) return [str];
910
+ var pre = m.pre;
911
+ var post = m.post.length ? expand2(m.post, false) : [""];
912
+ if (/\$$/.test(m.pre)) {
913
+ for (var k = 0; k < post.length; k++) {
914
+ var expansion = pre + "{" + m.body + "}" + post[k];
915
+ expansions.push(expansion);
916
+ }
917
+ } else {
918
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
919
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
920
+ var isSequence = isNumericSequence || isAlphaSequence;
921
+ var isOptions = m.body.indexOf(",") >= 0;
922
+ if (!isSequence && !isOptions) {
923
+ if (m.post.match(/,(?!,).*\}/)) {
924
+ str = m.pre + "{" + m.body + escClose + m.post;
925
+ return expand2(str);
926
+ }
927
+ return [str];
928
+ }
929
+ var n;
930
+ if (isSequence) {
931
+ n = m.body.split(/\.\./);
932
+ } else {
933
+ n = parseCommaParts(m.body);
934
+ if (n.length === 1) {
935
+ n = expand2(n[0], false).map(embrace);
936
+ if (n.length === 1) {
937
+ return post.map(function(p) {
938
+ return m.pre + n[0] + p;
939
+ });
940
+ }
941
+ }
942
+ }
943
+ var N;
944
+ if (isSequence) {
945
+ var x = numeric(n[0]);
946
+ var y = numeric(n[1]);
947
+ var width = Math.max(n[0].length, n[1].length);
948
+ var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
949
+ var test = lte;
950
+ var reverse = y < x;
951
+ if (reverse) {
952
+ incr *= -1;
953
+ test = gte;
954
+ }
955
+ var pad = n.some(isPadded);
956
+ N = [];
957
+ for (var i2 = x; test(i2, y); i2 += incr) {
958
+ var c;
959
+ if (isAlphaSequence) {
960
+ c = String.fromCharCode(i2);
961
+ if (c === "\\")
962
+ c = "";
963
+ } else {
964
+ c = String(i2);
965
+ if (pad) {
966
+ var need = width - c.length;
967
+ if (need > 0) {
968
+ var z = new Array(need + 1).join("0");
969
+ if (i2 < 0)
970
+ c = "-" + z + c.slice(1);
971
+ else
972
+ c = z + c;
973
+ }
974
+ }
975
+ }
976
+ N.push(c);
977
+ }
978
+ } else {
979
+ N = [];
980
+ for (var j = 0; j < n.length; j++) {
981
+ N.push.apply(N, expand2(n[j], false));
982
+ }
983
+ }
984
+ for (var j = 0; j < N.length; j++) {
985
+ for (var k = 0; k < post.length; k++) {
986
+ var expansion = pre + N[j] + post[k];
987
+ if (!isTop || isSequence || expansion)
988
+ expansions.push(expansion);
989
+ }
990
+ }
991
+ }
992
+ return expansions;
993
+ }
994
+ }
995
+ });
996
+
997
+ // src/utils/constants.ts
998
+ var SVG_NS = "http://www.w3.org/2000/svg";
999
+ var HTML_NS = "http://www.w3.org/1999/xhtml";
1000
+ var reWireGetterSetter = (instance, hostRef) => {
1001
+ var _a;
1002
+ const cmpMeta = hostRef.$cmpMeta$;
1003
+ const members = Object.entries((_a = cmpMeta.$members$) != null ? _a : {});
1004
+ members.map(([memberName, [memberFlags]]) => {
1005
+ if ((memberFlags & 31 /* Prop */ || memberFlags & 32 /* State */)) {
1006
+ const ogValue = instance[memberName];
1007
+ const ogDescriptor = getPropertyDescriptor(Object.getPrototypeOf(instance), memberName) || Object.getOwnPropertyDescriptor(instance, memberName);
1008
+ if (ogDescriptor) {
1009
+ Object.defineProperty(instance, memberName, {
1010
+ get() {
1011
+ return ogDescriptor.get.call(this);
1012
+ },
1013
+ set(newValue) {
1014
+ ogDescriptor.set.call(this, newValue);
1015
+ },
1016
+ configurable: true,
1017
+ enumerable: true
1018
+ });
1019
+ }
1020
+ instance[memberName] = hostRef.$instanceValues$.has(memberName) ? hostRef.$instanceValues$.get(memberName) : ogValue;
1021
+ }
1022
+ });
1023
+ };
1024
+ function getPropertyDescriptor(obj, memberName) {
1025
+ while (obj) {
1026
+ const desc = Object.getOwnPropertyDescriptor(obj, memberName);
1027
+ if (desc == null ? void 0 : desc.get) return desc;
1028
+ obj = Object.getPrototypeOf(obj);
1029
+ }
1030
+ return void 0;
1031
+ }
1032
+
1033
+ // src/client/client-host-ref.ts
1034
+ var getHostRef = (ref) => {
1035
+ if (ref.__stencil__getHostRef) {
1036
+ return ref.__stencil__getHostRef();
1037
+ }
1038
+ return void 0;
1039
+ };
1040
+ var registerInstance = (lazyInstance, hostRef) => {
1041
+ if (!hostRef) return;
1042
+ lazyInstance.__stencil__getHostRef = () => hostRef;
1043
+ hostRef.$lazyInstance$ = lazyInstance;
1044
+ if (hostRef.$cmpMeta$.$flags$ & 512 /* hasModernPropertyDecls */ && (BUILD.prop)) {
1045
+ reWireGetterSetter(lazyInstance, hostRef);
1046
+ }
1047
+ };
1048
+ var registerHost = (hostElement, cmpMeta) => {
1049
+ const hostRef = {
1050
+ $flags$: 0,
1051
+ $hostElement$: hostElement,
1052
+ $cmpMeta$: cmpMeta,
1053
+ $instanceValues$: /* @__PURE__ */ new Map(),
1054
+ $serializerValues$: /* @__PURE__ */ new Map()
1055
+ };
1056
+ {
1057
+ hostRef.$onReadyPromise$ = new Promise((r) => hostRef.$onReadyResolve$ = r);
1058
+ hostElement["s-p"] = [];
1059
+ hostElement["s-rc"] = [];
1060
+ }
1061
+ {
1062
+ hostRef.$fetchedCbList$ = [];
1063
+ }
1064
+ const ref = hostRef;
1065
+ hostElement.__stencil__getHostRef = () => ref;
1066
+ return ref;
1067
+ };
1068
+ var isMemberInElement = (elm, memberName) => memberName in elm;
1069
+ var consoleError = (e, el) => (0, console.error)(e, el);
1070
+
1071
+ // src/client/client-load-module.ts
1072
+ var cmpModules = /* @__PURE__ */ new Map();
1073
+ var loadModule = (cmpMeta, hostRef, hmrVersionId) => {
1074
+ const exportName = cmpMeta.$tagName$.replace(/-/g, "_");
1075
+ const bundleId = cmpMeta.$lazyBundleId$;
1076
+ if (!bundleId) {
1077
+ return void 0;
1078
+ }
1079
+ const module = cmpModules.get(bundleId) ;
1080
+ if (module) {
1081
+ return module[exportName];
1082
+ }
1083
+ /*!__STENCIL_STATIC_IMPORT_SWITCH__*/
1084
+ return import(
1085
+ /* @vite-ignore */
1086
+ /* webpackInclude: /\.entry\.js$/ */
1087
+ /* webpackExclude: /\.system\.entry\.js$/ */
1088
+ /* webpackMode: "lazy" */
1089
+ `./${bundleId}.entry.js${""}`
1090
+ ).then(
1091
+ (importedModule) => {
1092
+ {
1093
+ cmpModules.set(bundleId, importedModule);
1094
+ }
1095
+ return importedModule[exportName];
1096
+ },
1097
+ (e) => {
1098
+ consoleError(e, hostRef.$hostElement$);
1099
+ }
1100
+ );
1101
+ };
1102
+
1103
+ // src/client/client-style.ts
1104
+ var styles = /* @__PURE__ */ new Map();
1105
+ var HYDRATED_CSS = "{visibility:hidden}.hydrated{visibility:inherit}";
1106
+ var SLOT_FB_CSS = "slot-fb{display:contents}slot-fb[hidden]{display:none}";
1107
+ var win = typeof window !== "undefined" ? window : {};
1108
+ var plt = {
1109
+ $flags$: 0,
1110
+ $resourcesUrl$: "",
1111
+ jmp: (h2) => h2(),
1112
+ raf: (h2) => requestAnimationFrame(h2),
1113
+ ael: (el, eventName, listener, opts) => el.addEventListener(eventName, listener, opts),
1114
+ rel: (el, eventName, listener, opts) => el.removeEventListener(eventName, listener, opts),
1115
+ ce: (eventName, opts) => new CustomEvent(eventName, opts)
1116
+ };
1117
+ var promiseResolve = (v) => Promise.resolve(v);
1118
+ var supportsConstructableStylesheets = /* @__PURE__ */ (() => {
1119
+ try {
1120
+ if (!win.document.adoptedStyleSheets) {
1121
+ return false;
1122
+ }
1123
+ new CSSStyleSheet();
1124
+ return typeof new CSSStyleSheet().replaceSync === "function";
1125
+ } catch (e) {
1126
+ }
1127
+ return false;
1128
+ })() ;
1129
+ var supportsMutableAdoptedStyleSheets = supportsConstructableStylesheets ? /* @__PURE__ */ (() => !!win.document && Object.getOwnPropertyDescriptor(win.document.adoptedStyleSheets, "length").writable)() : false;
1130
+ var queuePending = false;
1131
+ var queueDomReads = [];
1132
+ var queueDomWrites = [];
1133
+ var queueTask = (queue, write) => (cb) => {
1134
+ queue.push(cb);
1135
+ if (!queuePending) {
1136
+ queuePending = true;
1137
+ if (write && plt.$flags$ & 4 /* queueSync */) {
1138
+ nextTick(flush);
1139
+ } else {
1140
+ plt.raf(flush);
1141
+ }
1142
+ }
1143
+ };
1144
+ var consume = (queue) => {
1145
+ for (let i2 = 0; i2 < queue.length; i2++) {
1146
+ try {
1147
+ queue[i2](performance.now());
1148
+ } catch (e) {
1149
+ consoleError(e);
1150
+ }
1151
+ }
1152
+ queue.length = 0;
1153
+ };
1154
+ var flush = () => {
1155
+ consume(queueDomReads);
1156
+ {
1157
+ consume(queueDomWrites);
1158
+ if (queuePending = queueDomReads.length > 0) {
1159
+ plt.raf(flush);
1160
+ }
1161
+ }
1162
+ };
1163
+ var nextTick = (cb) => promiseResolve().then(cb);
1164
+ var writeTask = /* @__PURE__ */ queueTask(queueDomWrites, true);
1165
+ var isComplexType = (o) => {
1166
+ o = typeof o;
1167
+ return o === "object" || o === "function";
1168
+ };
1169
+
1170
+ // node_modules/minimatch/dist/esm/index.js
1171
+ var import_brace_expansion = __toESM(require_brace_expansion());
1172
+
1173
+ // node_modules/minimatch/dist/esm/assert-valid-pattern.js
1174
+ var MAX_PATTERN_LENGTH = 1024 * 64;
1175
+ var assertValidPattern = (pattern) => {
1176
+ if (typeof pattern !== "string") {
1177
+ throw new TypeError("invalid pattern");
1178
+ }
1179
+ if (pattern.length > MAX_PATTERN_LENGTH) {
1180
+ throw new TypeError("pattern is too long");
1181
+ }
1182
+ };
1183
+
1184
+ // node_modules/minimatch/dist/esm/brace-expressions.js
1185
+ var posixClasses = {
1186
+ "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
1187
+ "[:alpha:]": ["\\p{L}\\p{Nl}", true],
1188
+ "[:ascii:]": ["\\x00-\\x7f", false],
1189
+ "[:blank:]": ["\\p{Zs}\\t", true],
1190
+ "[:cntrl:]": ["\\p{Cc}", true],
1191
+ "[:digit:]": ["\\p{Nd}", true],
1192
+ "[:graph:]": ["\\p{Z}\\p{C}", true, true],
1193
+ "[:lower:]": ["\\p{Ll}", true],
1194
+ "[:print:]": ["\\p{C}", true],
1195
+ "[:punct:]": ["\\p{P}", true],
1196
+ "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
1197
+ "[:upper:]": ["\\p{Lu}", true],
1198
+ "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
1199
+ "[:xdigit:]": ["A-Fa-f0-9", false]
1200
+ };
1201
+ var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
1202
+ var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
1203
+ var rangesToString = (ranges) => ranges.join("");
1204
+ var parseClass = (glob, position) => {
1205
+ const pos = position;
1206
+ if (glob.charAt(pos) !== "[") {
1207
+ throw new Error("not in a brace expression");
1208
+ }
1209
+ const ranges = [];
1210
+ const negs = [];
1211
+ let i2 = pos + 1;
1212
+ let sawStart = false;
1213
+ let uflag = false;
1214
+ let escaping = false;
1215
+ let negate = false;
1216
+ let endPos = pos;
1217
+ let rangeStart = "";
1218
+ WHILE: while (i2 < glob.length) {
1219
+ const c = glob.charAt(i2);
1220
+ if ((c === "!" || c === "^") && i2 === pos + 1) {
1221
+ negate = true;
1222
+ i2++;
1223
+ continue;
1224
+ }
1225
+ if (c === "]" && sawStart && !escaping) {
1226
+ endPos = i2 + 1;
1227
+ break;
1228
+ }
1229
+ sawStart = true;
1230
+ if (c === "\\") {
1231
+ if (!escaping) {
1232
+ escaping = true;
1233
+ i2++;
1234
+ continue;
1235
+ }
1236
+ }
1237
+ if (c === "[" && !escaping) {
1238
+ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
1239
+ if (glob.startsWith(cls, i2)) {
1240
+ if (rangeStart) {
1241
+ return ["$.", false, glob.length - pos, true];
1242
+ }
1243
+ i2 += cls.length;
1244
+ if (neg)
1245
+ negs.push(unip);
1246
+ else
1247
+ ranges.push(unip);
1248
+ uflag = uflag || u;
1249
+ continue WHILE;
1250
+ }
1251
+ }
1252
+ }
1253
+ escaping = false;
1254
+ if (rangeStart) {
1255
+ if (c > rangeStart) {
1256
+ ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
1257
+ } else if (c === rangeStart) {
1258
+ ranges.push(braceEscape(c));
1259
+ }
1260
+ rangeStart = "";
1261
+ i2++;
1262
+ continue;
1263
+ }
1264
+ if (glob.startsWith("-]", i2 + 1)) {
1265
+ ranges.push(braceEscape(c + "-"));
1266
+ i2 += 2;
1267
+ continue;
1268
+ }
1269
+ if (glob.startsWith("-", i2 + 1)) {
1270
+ rangeStart = c;
1271
+ i2 += 2;
1272
+ continue;
1273
+ }
1274
+ ranges.push(braceEscape(c));
1275
+ i2++;
1276
+ }
1277
+ if (endPos < i2) {
1278
+ return ["", false, 0, false];
1279
+ }
1280
+ if (!ranges.length && !negs.length) {
1281
+ return ["$.", false, glob.length - pos, true];
1282
+ }
1283
+ if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
1284
+ const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
1285
+ return [regexpEscape(r), false, endPos - pos, false];
1286
+ }
1287
+ const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
1288
+ const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
1289
+ const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
1290
+ return [comb, uflag, endPos - pos, true];
1291
+ };
1292
+
1293
+ // node_modules/minimatch/dist/esm/unescape.js
1294
+ var unescape = (s, { windowsPathsNoEscape = false } = {}) => {
1295
+ return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
1296
+ };
1297
+
1298
+ // node_modules/minimatch/dist/esm/ast.js
1299
+ var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
1300
+ var isExtglobType = (c) => types.has(c);
1301
+ var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
1302
+ var startNoDot = "(?!\\.)";
1303
+ var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
1304
+ var justDots = /* @__PURE__ */ new Set(["..", "."]);
1305
+ var reSpecials = new Set("().*{}+?[]^$\\!");
1306
+ var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
1307
+ var qmark = "[^/]";
1308
+ var star = qmark + "*?";
1309
+ var starNoEmpty = qmark + "+?";
1310
+ var _root, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _AST_instances, fillNegs_fn, _AST_static, parseAST_fn, partsToRegExp_fn, parseGlob_fn;
1311
+ var _AST = class _AST {
1312
+ constructor(type, parent, options = {}) {
1313
+ __privateAdd(this, _AST_instances);
1314
+ __publicField(this, "type");
1315
+ __privateAdd(this, _root);
1316
+ __privateAdd(this, _hasMagic);
1317
+ __privateAdd(this, _uflag, false);
1318
+ __privateAdd(this, _parts, []);
1319
+ __privateAdd(this, _parent);
1320
+ __privateAdd(this, _parentIndex);
1321
+ __privateAdd(this, _negs);
1322
+ __privateAdd(this, _filledNegs, false);
1323
+ __privateAdd(this, _options);
1324
+ __privateAdd(this, _toString);
1325
+ // set to true if it's an extglob with no children
1326
+ // (which really means one child of '')
1327
+ __privateAdd(this, _emptyExt, false);
1328
+ this.type = type;
1329
+ if (type)
1330
+ __privateSet(this, _hasMagic, true);
1331
+ __privateSet(this, _parent, parent);
1332
+ __privateSet(this, _root, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _root) : this);
1333
+ __privateSet(this, _options, __privateGet(this, _root) === this ? options : __privateGet(__privateGet(this, _root), _options));
1334
+ __privateSet(this, _negs, __privateGet(this, _root) === this ? [] : __privateGet(__privateGet(this, _root), _negs));
1335
+ if (type === "!" && !__privateGet(__privateGet(this, _root), _filledNegs))
1336
+ __privateGet(this, _negs).push(this);
1337
+ __privateSet(this, _parentIndex, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0);
1338
+ }
1339
+ get hasMagic() {
1340
+ if (__privateGet(this, _hasMagic) !== void 0)
1341
+ return __privateGet(this, _hasMagic);
1342
+ for (const p of __privateGet(this, _parts)) {
1343
+ if (typeof p === "string")
1344
+ continue;
1345
+ if (p.type || p.hasMagic)
1346
+ return __privateSet(this, _hasMagic, true);
1347
+ }
1348
+ return __privateGet(this, _hasMagic);
1349
+ }
1350
+ // reconstructs the pattern
1351
+ toString() {
1352
+ if (__privateGet(this, _toString) !== void 0)
1353
+ return __privateGet(this, _toString);
1354
+ if (!this.type) {
1355
+ return __privateSet(this, _toString, __privateGet(this, _parts).map((p) => String(p)).join(""));
1356
+ } else {
1357
+ return __privateSet(this, _toString, this.type + "(" + __privateGet(this, _parts).map((p) => String(p)).join("|") + ")");
1358
+ }
1359
+ }
1360
+ push(...parts) {
1361
+ for (const p of parts) {
1362
+ if (p === "")
1363
+ continue;
1364
+ if (typeof p !== "string" && !(p instanceof _AST && __privateGet(p, _parent) === this)) {
1365
+ throw new Error("invalid part: " + p);
1366
+ }
1367
+ __privateGet(this, _parts).push(p);
1368
+ }
1369
+ }
1370
+ toJSON() {
1371
+ var _a;
1372
+ const ret = this.type === null ? __privateGet(this, _parts).slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...__privateGet(this, _parts).map((p) => p.toJSON())];
1373
+ if (this.isStart() && !this.type)
1374
+ ret.unshift([]);
1375
+ if (this.isEnd() && (this === __privateGet(this, _root) || __privateGet(__privateGet(this, _root), _filledNegs) && ((_a = __privateGet(this, _parent)) == null ? void 0 : _a.type) === "!")) {
1376
+ ret.push({});
1377
+ }
1378
+ return ret;
1379
+ }
1380
+ isStart() {
1381
+ var _a;
1382
+ if (__privateGet(this, _root) === this)
1383
+ return true;
1384
+ if (!((_a = __privateGet(this, _parent)) == null ? void 0 : _a.isStart()))
1385
+ return false;
1386
+ if (__privateGet(this, _parentIndex) === 0)
1387
+ return true;
1388
+ const p = __privateGet(this, _parent);
1389
+ for (let i2 = 0; i2 < __privateGet(this, _parentIndex); i2++) {
1390
+ const pp = __privateGet(p, _parts)[i2];
1391
+ if (!(pp instanceof _AST && pp.type === "!")) {
1392
+ return false;
1393
+ }
1394
+ }
1395
+ return true;
1396
+ }
1397
+ isEnd() {
1398
+ var _a, _b, _c;
1399
+ if (__privateGet(this, _root) === this)
1400
+ return true;
1401
+ if (((_a = __privateGet(this, _parent)) == null ? void 0 : _a.type) === "!")
1402
+ return true;
1403
+ if (!((_b = __privateGet(this, _parent)) == null ? void 0 : _b.isEnd()))
1404
+ return false;
1405
+ if (!this.type)
1406
+ return (_c = __privateGet(this, _parent)) == null ? void 0 : _c.isEnd();
1407
+ const pl = __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0;
1408
+ return __privateGet(this, _parentIndex) === pl - 1;
1409
+ }
1410
+ copyIn(part) {
1411
+ if (typeof part === "string")
1412
+ this.push(part);
1413
+ else
1414
+ this.push(part.clone(this));
1415
+ }
1416
+ clone(parent) {
1417
+ const c = new _AST(this.type, parent);
1418
+ for (const p of __privateGet(this, _parts)) {
1419
+ c.copyIn(p);
1420
+ }
1421
+ return c;
1422
+ }
1423
+ static fromGlob(pattern, options = {}) {
1424
+ var _a;
1425
+ const ast = new _AST(null, void 0, options);
1426
+ __privateMethod(_a = _AST, _AST_static, parseAST_fn).call(_a, pattern, ast, 0, options);
1427
+ return ast;
1428
+ }
1429
+ // returns the regular expression if there's magic, or the unescaped
1430
+ // string if not.
1431
+ toMMPattern() {
1432
+ if (this !== __privateGet(this, _root))
1433
+ return __privateGet(this, _root).toMMPattern();
1434
+ const glob = this.toString();
1435
+ const [re, body, hasMagic, uflag] = this.toRegExpSource();
1436
+ const anyMagic = hasMagic || __privateGet(this, _hasMagic) || __privateGet(this, _options).nocase && !__privateGet(this, _options).nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase();
1437
+ if (!anyMagic) {
1438
+ return body;
1439
+ }
1440
+ const flags = (__privateGet(this, _options).nocase ? "i" : "") + (uflag ? "u" : "");
1441
+ return Object.assign(new RegExp(`^${re}$`, flags), {
1442
+ _src: re,
1443
+ _glob: glob
1444
+ });
1445
+ }
1446
+ get options() {
1447
+ return __privateGet(this, _options);
1448
+ }
1449
+ // returns the string match, the regexp source, whether there's magic
1450
+ // in the regexp (so a regular expression is required) and whether or
1451
+ // not the uflag is needed for the regular expression (for posix classes)
1452
+ // TODO: instead of injecting the start/end at this point, just return
1453
+ // the BODY of the regexp, along with the start/end portions suitable
1454
+ // for binding the start/end in either a joined full-path makeRe context
1455
+ // (where we bind to (^|/), or a standalone matchPart context (where
1456
+ // we bind to ^, and not /). Otherwise slashes get duped!
1457
+ //
1458
+ // In part-matching mode, the start is:
1459
+ // - if not isStart: nothing
1460
+ // - if traversal possible, but not allowed: ^(?!\.\.?$)
1461
+ // - if dots allowed or not possible: ^
1462
+ // - if dots possible and not allowed: ^(?!\.)
1463
+ // end is:
1464
+ // - if not isEnd(): nothing
1465
+ // - else: $
1466
+ //
1467
+ // In full-path matching mode, we put the slash at the START of the
1468
+ // pattern, so start is:
1469
+ // - if first pattern: same as part-matching mode
1470
+ // - if not isStart(): nothing
1471
+ // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
1472
+ // - if dots allowed or not possible: /
1473
+ // - if dots possible and not allowed: /(?!\.)
1474
+ // end is:
1475
+ // - if last pattern, same as part-matching mode
1476
+ // - else nothing
1477
+ //
1478
+ // Always put the (?:$|/) on negated tails, though, because that has to be
1479
+ // there to bind the end of the negated pattern portion, and it's easier to
1480
+ // just stick it in now rather than try to inject it later in the middle of
1481
+ // the pattern.
1482
+ //
1483
+ // We can just always return the same end, and leave it up to the caller
1484
+ // to know whether it's going to be used joined or in parts.
1485
+ // And, if the start is adjusted slightly, can do the same there:
1486
+ // - if not isStart: nothing
1487
+ // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
1488
+ // - if dots allowed or not possible: (?:/|^)
1489
+ // - if dots possible and not allowed: (?:/|^)(?!\.)
1490
+ //
1491
+ // But it's better to have a simpler binding without a conditional, for
1492
+ // performance, so probably better to return both start options.
1493
+ //
1494
+ // Then the caller just ignores the end if it's not the first pattern,
1495
+ // and the start always gets applied.
1496
+ //
1497
+ // But that's always going to be $ if it's the ending pattern, or nothing,
1498
+ // so the caller can just attach $ at the end of the pattern when building.
1499
+ //
1500
+ // So the todo is:
1501
+ // - better detect what kind of start is needed
1502
+ // - return both flavors of starting pattern
1503
+ // - attach $ at the end of the pattern when creating the actual RegExp
1504
+ //
1505
+ // Ah, but wait, no, that all only applies to the root when the first pattern
1506
+ // is not an extglob. If the first pattern IS an extglob, then we need all
1507
+ // that dot prevention biz to live in the extglob portions, because eg
1508
+ // +(*|.x*) can match .xy but not .yx.
1509
+ //
1510
+ // So, return the two flavors if it's #root and the first child is not an
1511
+ // AST, otherwise leave it to the child AST to handle it, and there,
1512
+ // use the (?:^|/) style of start binding.
1513
+ //
1514
+ // Even simplified further:
1515
+ // - Since the start for a join is eg /(?!\.) and the start for a part
1516
+ // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
1517
+ // or start or whatever) and prepend ^ or / at the Regexp construction.
1518
+ toRegExpSource(allowDot) {
1519
+ var _a;
1520
+ const dot = allowDot != null ? allowDot : !!__privateGet(this, _options).dot;
1521
+ if (__privateGet(this, _root) === this)
1522
+ __privateMethod(this, _AST_instances, fillNegs_fn).call(this);
1523
+ if (!this.type) {
1524
+ const noEmpty = this.isStart() && this.isEnd();
1525
+ const src = __privateGet(this, _parts).map((p) => {
1526
+ var _a2;
1527
+ const [re, _, hasMagic, uflag] = typeof p === "string" ? __privateMethod(_a2 = _AST, _AST_static, parseGlob_fn).call(_a2, p, __privateGet(this, _hasMagic), noEmpty) : p.toRegExpSource(allowDot);
1528
+ __privateSet(this, _hasMagic, __privateGet(this, _hasMagic) || hasMagic);
1529
+ __privateSet(this, _uflag, __privateGet(this, _uflag) || uflag);
1530
+ return re;
1531
+ }).join("");
1532
+ let start2 = "";
1533
+ if (this.isStart()) {
1534
+ if (typeof __privateGet(this, _parts)[0] === "string") {
1535
+ const dotTravAllowed = __privateGet(this, _parts).length === 1 && justDots.has(__privateGet(this, _parts)[0]);
1536
+ if (!dotTravAllowed) {
1537
+ const aps = addPatternStart;
1538
+ const needNoTrav = (
1539
+ // dots are allowed, and the pattern starts with [ or .
1540
+ dot && aps.has(src.charAt(0)) || // the pattern starts with \., and then [ or .
1541
+ src.startsWith("\\.") && aps.has(src.charAt(2)) || // the pattern starts with \.\., and then [ or .
1542
+ src.startsWith("\\.\\.") && aps.has(src.charAt(4))
1543
+ );
1544
+ const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
1545
+ start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
1546
+ }
1547
+ }
1548
+ }
1549
+ let end = "";
1550
+ if (this.isEnd() && __privateGet(__privateGet(this, _root), _filledNegs) && ((_a = __privateGet(this, _parent)) == null ? void 0 : _a.type) === "!") {
1551
+ end = "(?:$|\\/)";
1552
+ }
1553
+ const final2 = start2 + src + end;
1554
+ return [
1555
+ final2,
1556
+ unescape(src),
1557
+ __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)),
1558
+ __privateGet(this, _uflag)
1559
+ ];
1560
+ }
1561
+ const repeated = this.type === "*" || this.type === "+";
1562
+ const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
1563
+ let body = __privateMethod(this, _AST_instances, partsToRegExp_fn).call(this, dot);
1564
+ if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
1565
+ const s = this.toString();
1566
+ __privateSet(this, _parts, [s]);
1567
+ this.type = null;
1568
+ __privateSet(this, _hasMagic, void 0);
1569
+ return [s, unescape(this.toString()), false, false];
1570
+ }
1571
+ let bodyDotAllowed = !repeated || allowDot || dot || false ? "" : __privateMethod(this, _AST_instances, partsToRegExp_fn).call(this, true);
1572
+ if (bodyDotAllowed === body) {
1573
+ bodyDotAllowed = "";
1574
+ }
1575
+ if (bodyDotAllowed) {
1576
+ body = `(?:${body})(?:${bodyDotAllowed})*?`;
1577
+ }
1578
+ let final = "";
1579
+ if (this.type === "!" && __privateGet(this, _emptyExt)) {
1580
+ final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;
1581
+ } else {
1582
+ const close = this.type === "!" ? (
1583
+ // !() must match something,but !(x) can match ''
1584
+ "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")"
1585
+ ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;
1586
+ final = start + body + close;
1587
+ }
1588
+ return [
1589
+ final,
1590
+ unescape(body),
1591
+ __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)),
1592
+ __privateGet(this, _uflag)
1593
+ ];
1594
+ }
1595
+ };
1596
+ _root = new WeakMap();
1597
+ _hasMagic = new WeakMap();
1598
+ _uflag = new WeakMap();
1599
+ _parts = new WeakMap();
1600
+ _parent = new WeakMap();
1601
+ _parentIndex = new WeakMap();
1602
+ _negs = new WeakMap();
1603
+ _filledNegs = new WeakMap();
1604
+ _options = new WeakMap();
1605
+ _toString = new WeakMap();
1606
+ _emptyExt = new WeakMap();
1607
+ _AST_instances = new WeakSet();
1608
+ fillNegs_fn = function() {
1609
+ if (this !== __privateGet(this, _root))
1610
+ throw new Error("should only call on root");
1611
+ if (__privateGet(this, _filledNegs))
1612
+ return this;
1613
+ this.toString();
1614
+ __privateSet(this, _filledNegs, true);
1615
+ let n;
1616
+ while (n = __privateGet(this, _negs).pop()) {
1617
+ if (n.type !== "!")
1618
+ continue;
1619
+ let p = n;
1620
+ let pp = __privateGet(p, _parent);
1621
+ while (pp) {
1622
+ for (let i2 = __privateGet(p, _parentIndex) + 1; !pp.type && i2 < __privateGet(pp, _parts).length; i2++) {
1623
+ for (const part of __privateGet(n, _parts)) {
1624
+ if (typeof part === "string") {
1625
+ throw new Error("string part in extglob AST??");
1626
+ }
1627
+ part.copyIn(__privateGet(pp, _parts)[i2]);
1628
+ }
1629
+ }
1630
+ p = pp;
1631
+ pp = __privateGet(p, _parent);
1632
+ }
1633
+ }
1634
+ return this;
1635
+ };
1636
+ _AST_static = new WeakSet();
1637
+ parseAST_fn = function(str, ast, pos, opt) {
1638
+ var _a, _b;
1639
+ let escaping = false;
1640
+ let inBrace = false;
1641
+ let braceStart = -1;
1642
+ let braceNeg = false;
1643
+ if (ast.type === null) {
1644
+ let i3 = pos;
1645
+ let acc2 = "";
1646
+ while (i3 < str.length) {
1647
+ const c = str.charAt(i3++);
1648
+ if (escaping || c === "\\") {
1649
+ escaping = !escaping;
1650
+ acc2 += c;
1651
+ continue;
1652
+ }
1653
+ if (inBrace) {
1654
+ if (i3 === braceStart + 1) {
1655
+ if (c === "^" || c === "!") {
1656
+ braceNeg = true;
1657
+ }
1658
+ } else if (c === "]" && !(i3 === braceStart + 2 && braceNeg)) {
1659
+ inBrace = false;
1660
+ }
1661
+ acc2 += c;
1662
+ continue;
1663
+ } else if (c === "[") {
1664
+ inBrace = true;
1665
+ braceStart = i3;
1666
+ braceNeg = false;
1667
+ acc2 += c;
1668
+ continue;
1669
+ }
1670
+ if (!opt.noext && isExtglobType(c) && str.charAt(i3) === "(") {
1671
+ ast.push(acc2);
1672
+ acc2 = "";
1673
+ const ext2 = new _AST(c, ast);
1674
+ i3 = __privateMethod(_a = _AST, _AST_static, parseAST_fn).call(_a, str, ext2, i3, opt);
1675
+ ast.push(ext2);
1676
+ continue;
1677
+ }
1678
+ acc2 += c;
1679
+ }
1680
+ ast.push(acc2);
1681
+ return i3;
1682
+ }
1683
+ let i2 = pos + 1;
1684
+ let part = new _AST(null, ast);
1685
+ const parts = [];
1686
+ let acc = "";
1687
+ while (i2 < str.length) {
1688
+ const c = str.charAt(i2++);
1689
+ if (escaping || c === "\\") {
1690
+ escaping = !escaping;
1691
+ acc += c;
1692
+ continue;
1693
+ }
1694
+ if (inBrace) {
1695
+ if (i2 === braceStart + 1) {
1696
+ if (c === "^" || c === "!") {
1697
+ braceNeg = true;
1698
+ }
1699
+ } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {
1700
+ inBrace = false;
1701
+ }
1702
+ acc += c;
1703
+ continue;
1704
+ } else if (c === "[") {
1705
+ inBrace = true;
1706
+ braceStart = i2;
1707
+ braceNeg = false;
1708
+ acc += c;
1709
+ continue;
1710
+ }
1711
+ if (isExtglobType(c) && str.charAt(i2) === "(") {
1712
+ part.push(acc);
1713
+ acc = "";
1714
+ const ext2 = new _AST(c, part);
1715
+ part.push(ext2);
1716
+ i2 = __privateMethod(_b = _AST, _AST_static, parseAST_fn).call(_b, str, ext2, i2, opt);
1717
+ continue;
1718
+ }
1719
+ if (c === "|") {
1720
+ part.push(acc);
1721
+ acc = "";
1722
+ parts.push(part);
1723
+ part = new _AST(null, ast);
1724
+ continue;
1725
+ }
1726
+ if (c === ")") {
1727
+ if (acc === "" && __privateGet(ast, _parts).length === 0) {
1728
+ __privateSet(ast, _emptyExt, true);
1729
+ }
1730
+ part.push(acc);
1731
+ acc = "";
1732
+ ast.push(...parts, part);
1733
+ return i2;
1734
+ }
1735
+ acc += c;
1736
+ }
1737
+ ast.type = null;
1738
+ __privateSet(ast, _hasMagic, void 0);
1739
+ __privateSet(ast, _parts, [str.substring(pos - 1)]);
1740
+ return i2;
1741
+ };
1742
+ partsToRegExp_fn = function(dot) {
1743
+ return __privateGet(this, _parts).map((p) => {
1744
+ if (typeof p === "string") {
1745
+ throw new Error("string type in extglob ast??");
1746
+ }
1747
+ const [re, _, _hasMagic2, uflag] = p.toRegExpSource(dot);
1748
+ __privateSet(this, _uflag, __privateGet(this, _uflag) || uflag);
1749
+ return re;
1750
+ }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
1751
+ };
1752
+ parseGlob_fn = function(glob, hasMagic, noEmpty = false) {
1753
+ let escaping = false;
1754
+ let re = "";
1755
+ let uflag = false;
1756
+ for (let i2 = 0; i2 < glob.length; i2++) {
1757
+ const c = glob.charAt(i2);
1758
+ if (escaping) {
1759
+ escaping = false;
1760
+ re += (reSpecials.has(c) ? "\\" : "") + c;
1761
+ continue;
1762
+ }
1763
+ if (c === "\\") {
1764
+ if (i2 === glob.length - 1) {
1765
+ re += "\\\\";
1766
+ } else {
1767
+ escaping = true;
1768
+ }
1769
+ continue;
1770
+ }
1771
+ if (c === "[") {
1772
+ const [src, needUflag, consumed, magic] = parseClass(glob, i2);
1773
+ if (consumed) {
1774
+ re += src;
1775
+ uflag = uflag || needUflag;
1776
+ i2 += consumed - 1;
1777
+ hasMagic = hasMagic || magic;
1778
+ continue;
1779
+ }
1780
+ }
1781
+ if (c === "*") {
1782
+ if (noEmpty && glob === "*")
1783
+ re += starNoEmpty;
1784
+ else
1785
+ re += star;
1786
+ hasMagic = true;
1787
+ continue;
1788
+ }
1789
+ if (c === "?") {
1790
+ re += qmark;
1791
+ hasMagic = true;
1792
+ continue;
1793
+ }
1794
+ re += regExpEscape(c);
1795
+ }
1796
+ return [re, unescape(glob), !!hasMagic, uflag];
1797
+ };
1798
+ __privateAdd(_AST, _AST_static);
1799
+ var AST = _AST;
1800
+
1801
+ // node_modules/minimatch/dist/esm/escape.js
1802
+ var escape = (s, { windowsPathsNoEscape = false } = {}) => {
1803
+ return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
1804
+ };
1805
+
1806
+ // node_modules/minimatch/dist/esm/index.js
1807
+ var minimatch = (p, pattern, options = {}) => {
1808
+ assertValidPattern(pattern);
1809
+ if (!options.nocomment && pattern.charAt(0) === "#") {
1810
+ return false;
1811
+ }
1812
+ return new Minimatch(pattern, options).match(p);
1813
+ };
1814
+ var starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
1815
+ var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);
1816
+ var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);
1817
+ var starDotExtTestNocase = (ext2) => {
1818
+ ext2 = ext2.toLowerCase();
1819
+ return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);
1820
+ };
1821
+ var starDotExtTestNocaseDot = (ext2) => {
1822
+ ext2 = ext2.toLowerCase();
1823
+ return (f) => f.toLowerCase().endsWith(ext2);
1824
+ };
1825
+ var starDotStarRE = /^\*+\.\*+$/;
1826
+ var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");
1827
+ var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");
1828
+ var dotStarRE = /^\.\*+$/;
1829
+ var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");
1830
+ var starRE = /^\*+$/;
1831
+ var starTest = (f) => f.length !== 0 && !f.startsWith(".");
1832
+ var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";
1833
+ var qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
1834
+ var qmarksTestNocase = ([$0, ext2 = ""]) => {
1835
+ const noext = qmarksTestNoExt([$0]);
1836
+ if (!ext2)
1837
+ return noext;
1838
+ ext2 = ext2.toLowerCase();
1839
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
1840
+ };
1841
+ var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
1842
+ const noext = qmarksTestNoExtDot([$0]);
1843
+ if (!ext2)
1844
+ return noext;
1845
+ ext2 = ext2.toLowerCase();
1846
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
1847
+ };
1848
+ var qmarksTestDot = ([$0, ext2 = ""]) => {
1849
+ const noext = qmarksTestNoExtDot([$0]);
1850
+ return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
1851
+ };
1852
+ var qmarksTest = ([$0, ext2 = ""]) => {
1853
+ const noext = qmarksTestNoExt([$0]);
1854
+ return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
1855
+ };
1856
+ var qmarksTestNoExt = ([$0]) => {
1857
+ const len = $0.length;
1858
+ return (f) => f.length === len && !f.startsWith(".");
1859
+ };
1860
+ var qmarksTestNoExtDot = ([$0]) => {
1861
+ const len = $0.length;
1862
+ return (f) => f.length === len && f !== "." && f !== "..";
1863
+ };
1864
+ var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
1865
+ var path = {
1866
+ win32: { sep: "\\" },
1867
+ posix: { sep: "/" }
1868
+ };
1869
+ var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
1870
+ minimatch.sep = sep;
1871
+ var GLOBSTAR = Symbol("globstar **");
1872
+ minimatch.GLOBSTAR = GLOBSTAR;
1873
+ var qmark2 = "[^/]";
1874
+ var star2 = qmark2 + "*?";
1875
+ var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
1876
+ var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
1877
+ var filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
1878
+ minimatch.filter = filter;
1879
+ var ext = (a, b = {}) => Object.assign({}, a, b);
1880
+ var defaults = (def) => {
1881
+ if (!def || typeof def !== "object" || !Object.keys(def).length) {
1882
+ return minimatch;
1883
+ }
1884
+ const orig = minimatch;
1885
+ const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
1886
+ return Object.assign(m, {
1887
+ Minimatch: class Minimatch extends orig.Minimatch {
1888
+ constructor(pattern, options = {}) {
1889
+ super(pattern, ext(def, options));
1890
+ }
1891
+ static defaults(options) {
1892
+ return orig.defaults(ext(def, options)).Minimatch;
1893
+ }
1894
+ },
1895
+ AST: class AST extends orig.AST {
1896
+ /* c8 ignore start */
1897
+ constructor(type, parent, options = {}) {
1898
+ super(type, parent, ext(def, options));
1899
+ }
1900
+ /* c8 ignore stop */
1901
+ static fromGlob(pattern, options = {}) {
1902
+ return orig.AST.fromGlob(pattern, ext(def, options));
1903
+ }
1904
+ },
1905
+ unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
1906
+ escape: (s, options = {}) => orig.escape(s, ext(def, options)),
1907
+ filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
1908
+ defaults: (options) => orig.defaults(ext(def, options)),
1909
+ makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
1910
+ braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
1911
+ match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
1912
+ sep: orig.sep,
1913
+ GLOBSTAR
1914
+ });
1915
+ };
1916
+ minimatch.defaults = defaults;
1917
+ var braceExpand = (pattern, options = {}) => {
1918
+ assertValidPattern(pattern);
1919
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
1920
+ return [pattern];
1921
+ }
1922
+ return (0, import_brace_expansion.default)(pattern);
1923
+ };
1924
+ minimatch.braceExpand = braceExpand;
1925
+ var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
1926
+ minimatch.makeRe = makeRe;
1927
+ var match = (list, pattern, options = {}) => {
1928
+ const mm = new Minimatch(pattern, options);
1929
+ list = list.filter((f) => mm.match(f));
1930
+ if (mm.options.nonull && !list.length) {
1931
+ list.push(pattern);
1932
+ }
1933
+ return list;
1934
+ };
1935
+ minimatch.match = match;
1936
+ var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
1937
+ var regExpEscape2 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
1938
+ var Minimatch = class {
1939
+ options;
1940
+ set;
1941
+ pattern;
1942
+ windowsPathsNoEscape;
1943
+ nonegate;
1944
+ negate;
1945
+ comment;
1946
+ empty;
1947
+ preserveMultipleSlashes;
1948
+ partial;
1949
+ globSet;
1950
+ globParts;
1951
+ nocase;
1952
+ isWindows;
1953
+ platform;
1954
+ windowsNoMagicRoot;
1955
+ regexp;
1956
+ constructor(pattern, options = {}) {
1957
+ assertValidPattern(pattern);
1958
+ options = options || {};
1959
+ this.options = options;
1960
+ this.pattern = pattern;
1961
+ this.platform = options.platform || defaultPlatform;
1962
+ this.isWindows = this.platform === "win32";
1963
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
1964
+ if (this.windowsPathsNoEscape) {
1965
+ this.pattern = this.pattern.replace(/\\/g, "/");
1966
+ }
1967
+ this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
1968
+ this.regexp = null;
1969
+ this.negate = false;
1970
+ this.nonegate = !!options.nonegate;
1971
+ this.comment = false;
1972
+ this.empty = false;
1973
+ this.partial = !!options.partial;
1974
+ this.nocase = !!this.options.nocase;
1975
+ this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
1976
+ this.globSet = [];
1977
+ this.globParts = [];
1978
+ this.set = [];
1979
+ this.make();
1980
+ }
1981
+ hasMagic() {
1982
+ if (this.options.magicalBraces && this.set.length > 1) {
1983
+ return true;
1984
+ }
1985
+ for (const pattern of this.set) {
1986
+ for (const part of pattern) {
1987
+ if (typeof part !== "string")
1988
+ return true;
1989
+ }
1990
+ }
1991
+ return false;
1992
+ }
1993
+ debug(..._) {
1994
+ }
1995
+ make() {
1996
+ const pattern = this.pattern;
1997
+ const options = this.options;
1998
+ if (!options.nocomment && pattern.charAt(0) === "#") {
1999
+ this.comment = true;
2000
+ return;
2001
+ }
2002
+ if (!pattern) {
2003
+ this.empty = true;
2004
+ return;
2005
+ }
2006
+ this.parseNegate();
2007
+ this.globSet = [...new Set(this.braceExpand())];
2008
+ if (options.debug) {
2009
+ this.debug = (...args) => console.error(...args);
2010
+ }
2011
+ this.debug(this.pattern, this.globSet);
2012
+ const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
2013
+ this.globParts = this.preprocess(rawGlobParts);
2014
+ this.debug(this.pattern, this.globParts);
2015
+ let set = this.globParts.map((s, _, __) => {
2016
+ if (this.isWindows && this.windowsNoMagicRoot) {
2017
+ const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
2018
+ const isDrive = /^[a-z]:/i.test(s[0]);
2019
+ if (isUNC) {
2020
+ return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))];
2021
+ } else if (isDrive) {
2022
+ return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
2023
+ }
2024
+ }
2025
+ return s.map((ss) => this.parse(ss));
2026
+ });
2027
+ this.debug(this.pattern, set);
2028
+ this.set = set.filter((s) => s.indexOf(false) === -1);
2029
+ if (this.isWindows) {
2030
+ for (let i2 = 0; i2 < this.set.length; i2++) {
2031
+ const p = this.set[i2];
2032
+ if (p[0] === "" && p[1] === "" && this.globParts[i2][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
2033
+ p[2] = "?";
2034
+ }
2035
+ }
2036
+ }
2037
+ this.debug(this.pattern, this.set);
2038
+ }
2039
+ // various transforms to equivalent pattern sets that are
2040
+ // faster to process in a filesystem walk. The goal is to
2041
+ // eliminate what we can, and push all ** patterns as far
2042
+ // to the right as possible, even if it increases the number
2043
+ // of patterns that we have to process.
2044
+ preprocess(globParts) {
2045
+ if (this.options.noglobstar) {
2046
+ for (let i2 = 0; i2 < globParts.length; i2++) {
2047
+ for (let j = 0; j < globParts[i2].length; j++) {
2048
+ if (globParts[i2][j] === "**") {
2049
+ globParts[i2][j] = "*";
2050
+ }
2051
+ }
2052
+ }
2053
+ }
2054
+ const { optimizationLevel = 1 } = this.options;
2055
+ if (optimizationLevel >= 2) {
2056
+ globParts = this.firstPhasePreProcess(globParts);
2057
+ globParts = this.secondPhasePreProcess(globParts);
2058
+ } else if (optimizationLevel >= 1) {
2059
+ globParts = this.levelOneOptimize(globParts);
2060
+ } else {
2061
+ globParts = this.adjascentGlobstarOptimize(globParts);
2062
+ }
2063
+ return globParts;
2064
+ }
2065
+ // just get rid of adjascent ** portions
2066
+ adjascentGlobstarOptimize(globParts) {
2067
+ return globParts.map((parts) => {
2068
+ let gs = -1;
2069
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
2070
+ let i2 = gs;
2071
+ while (parts[i2 + 1] === "**") {
2072
+ i2++;
2073
+ }
2074
+ if (i2 !== gs) {
2075
+ parts.splice(gs, i2 - gs);
2076
+ }
2077
+ }
2078
+ return parts;
2079
+ });
2080
+ }
2081
+ // get rid of adjascent ** and resolve .. portions
2082
+ levelOneOptimize(globParts) {
2083
+ return globParts.map((parts) => {
2084
+ parts = parts.reduce((set, part) => {
2085
+ const prev = set[set.length - 1];
2086
+ if (part === "**" && prev === "**") {
2087
+ return set;
2088
+ }
2089
+ if (part === "..") {
2090
+ if (prev && prev !== ".." && prev !== "." && prev !== "**") {
2091
+ set.pop();
2092
+ return set;
2093
+ }
2094
+ }
2095
+ set.push(part);
2096
+ return set;
2097
+ }, []);
2098
+ return parts.length === 0 ? [""] : parts;
2099
+ });
2100
+ }
2101
+ levelTwoFileOptimize(parts) {
2102
+ if (!Array.isArray(parts)) {
2103
+ parts = this.slashSplit(parts);
2104
+ }
2105
+ let didSomething = false;
2106
+ do {
2107
+ didSomething = false;
2108
+ if (!this.preserveMultipleSlashes) {
2109
+ for (let i2 = 1; i2 < parts.length - 1; i2++) {
2110
+ const p = parts[i2];
2111
+ if (i2 === 1 && p === "" && parts[0] === "")
2112
+ continue;
2113
+ if (p === "." || p === "") {
2114
+ didSomething = true;
2115
+ parts.splice(i2, 1);
2116
+ i2--;
2117
+ }
2118
+ }
2119
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
2120
+ didSomething = true;
2121
+ parts.pop();
2122
+ }
2123
+ }
2124
+ let dd = 0;
2125
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
2126
+ const p = parts[dd - 1];
2127
+ if (p && p !== "." && p !== ".." && p !== "**") {
2128
+ didSomething = true;
2129
+ parts.splice(dd - 1, 2);
2130
+ dd -= 2;
2131
+ }
2132
+ }
2133
+ } while (didSomething);
2134
+ return parts.length === 0 ? [""] : parts;
2135
+ }
2136
+ // First phase: single-pattern processing
2137
+ // <pre> is 1 or more portions
2138
+ // <rest> is 1 or more portions
2139
+ // <p> is any portion other than ., .., '', or **
2140
+ // <e> is . or ''
2141
+ //
2142
+ // **/.. is *brutal* for filesystem walking performance, because
2143
+ // it effectively resets the recursive walk each time it occurs,
2144
+ // and ** cannot be reduced out by a .. pattern part like a regexp
2145
+ // or most strings (other than .., ., and '') can be.
2146
+ //
2147
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
2148
+ // <pre>/<e>/<rest> -> <pre>/<rest>
2149
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
2150
+ // **/**/<rest> -> **/<rest>
2151
+ //
2152
+ // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
2153
+ // this WOULD be allowed if ** did follow symlinks, or * didn't
2154
+ firstPhasePreProcess(globParts) {
2155
+ let didSomething = false;
2156
+ do {
2157
+ didSomething = false;
2158
+ for (let parts of globParts) {
2159
+ let gs = -1;
2160
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
2161
+ let gss = gs;
2162
+ while (parts[gss + 1] === "**") {
2163
+ gss++;
2164
+ }
2165
+ if (gss > gs) {
2166
+ parts.splice(gs + 1, gss - gs);
2167
+ }
2168
+ let next = parts[gs + 1];
2169
+ const p = parts[gs + 2];
2170
+ const p2 = parts[gs + 3];
2171
+ if (next !== "..")
2172
+ continue;
2173
+ if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
2174
+ continue;
2175
+ }
2176
+ didSomething = true;
2177
+ parts.splice(gs, 1);
2178
+ const other = parts.slice(0);
2179
+ other[gs] = "**";
2180
+ globParts.push(other);
2181
+ gs--;
2182
+ }
2183
+ if (!this.preserveMultipleSlashes) {
2184
+ for (let i2 = 1; i2 < parts.length - 1; i2++) {
2185
+ const p = parts[i2];
2186
+ if (i2 === 1 && p === "" && parts[0] === "")
2187
+ continue;
2188
+ if (p === "." || p === "") {
2189
+ didSomething = true;
2190
+ parts.splice(i2, 1);
2191
+ i2--;
2192
+ }
2193
+ }
2194
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
2195
+ didSomething = true;
2196
+ parts.pop();
2197
+ }
2198
+ }
2199
+ let dd = 0;
2200
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
2201
+ const p = parts[dd - 1];
2202
+ if (p && p !== "." && p !== ".." && p !== "**") {
2203
+ didSomething = true;
2204
+ const needDot = dd === 1 && parts[dd + 1] === "**";
2205
+ const splin = needDot ? ["."] : [];
2206
+ parts.splice(dd - 1, 2, ...splin);
2207
+ if (parts.length === 0)
2208
+ parts.push("");
2209
+ dd -= 2;
2210
+ }
2211
+ }
2212
+ }
2213
+ } while (didSomething);
2214
+ return globParts;
2215
+ }
2216
+ // second phase: multi-pattern dedupes
2217
+ // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
2218
+ // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
2219
+ // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
2220
+ //
2221
+ // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
2222
+ // ^-- not valid because ** doens't follow symlinks
2223
+ secondPhasePreProcess(globParts) {
2224
+ for (let i2 = 0; i2 < globParts.length - 1; i2++) {
2225
+ for (let j = i2 + 1; j < globParts.length; j++) {
2226
+ const matched = this.partsMatch(globParts[i2], globParts[j], !this.preserveMultipleSlashes);
2227
+ if (!matched)
2228
+ continue;
2229
+ globParts[i2] = matched;
2230
+ globParts[j] = [];
2231
+ }
2232
+ }
2233
+ return globParts.filter((gs) => gs.length);
2234
+ }
2235
+ partsMatch(a, b, emptyGSMatch = false) {
2236
+ let ai = 0;
2237
+ let bi = 0;
2238
+ let result = [];
2239
+ let which = "";
2240
+ while (ai < a.length && bi < b.length) {
2241
+ if (a[ai] === b[bi]) {
2242
+ result.push(which === "b" ? b[bi] : a[ai]);
2243
+ ai++;
2244
+ bi++;
2245
+ } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
2246
+ result.push(a[ai]);
2247
+ ai++;
2248
+ } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
2249
+ result.push(b[bi]);
2250
+ bi++;
2251
+ } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
2252
+ if (which === "b")
2253
+ return false;
2254
+ which = "a";
2255
+ result.push(a[ai]);
2256
+ ai++;
2257
+ bi++;
2258
+ } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
2259
+ if (which === "a")
2260
+ return false;
2261
+ which = "b";
2262
+ result.push(b[bi]);
2263
+ ai++;
2264
+ bi++;
2265
+ } else {
2266
+ return false;
2267
+ }
2268
+ }
2269
+ return a.length === b.length && result;
2270
+ }
2271
+ parseNegate() {
2272
+ if (this.nonegate)
2273
+ return;
2274
+ const pattern = this.pattern;
2275
+ let negate = false;
2276
+ let negateOffset = 0;
2277
+ for (let i2 = 0; i2 < pattern.length && pattern.charAt(i2) === "!"; i2++) {
2278
+ negate = !negate;
2279
+ negateOffset++;
2280
+ }
2281
+ if (negateOffset)
2282
+ this.pattern = pattern.slice(negateOffset);
2283
+ this.negate = negate;
2284
+ }
2285
+ // set partial to true to test if, for example,
2286
+ // "/a/b" matches the start of "/*/b/*/d"
2287
+ // Partial means, if you run out of file before you run
2288
+ // out of pattern, then that's fine, as long as all
2289
+ // the parts match.
2290
+ matchOne(file, pattern, partial = false) {
2291
+ const options = this.options;
2292
+ if (this.isWindows) {
2293
+ const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
2294
+ const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
2295
+ const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
2296
+ const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
2297
+ const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
2298
+ const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
2299
+ if (typeof fdi === "number" && typeof pdi === "number") {
2300
+ const [fd, pd] = [file[fdi], pattern[pdi]];
2301
+ if (fd.toLowerCase() === pd.toLowerCase()) {
2302
+ pattern[pdi] = fd;
2303
+ if (pdi > fdi) {
2304
+ pattern = pattern.slice(pdi);
2305
+ } else if (fdi > pdi) {
2306
+ file = file.slice(fdi);
2307
+ }
2308
+ }
2309
+ }
2310
+ }
2311
+ const { optimizationLevel = 1 } = this.options;
2312
+ if (optimizationLevel >= 2) {
2313
+ file = this.levelTwoFileOptimize(file);
2314
+ }
2315
+ this.debug("matchOne", this, { file, pattern });
2316
+ this.debug("matchOne", file.length, pattern.length);
2317
+ for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
2318
+ this.debug("matchOne loop");
2319
+ var p = pattern[pi];
2320
+ var f = file[fi];
2321
+ this.debug(pattern, p, f);
2322
+ if (p === false) {
2323
+ return false;
2324
+ }
2325
+ if (p === GLOBSTAR) {
2326
+ this.debug("GLOBSTAR", [pattern, p, f]);
2327
+ var fr = fi;
2328
+ var pr = pi + 1;
2329
+ if (pr === pl) {
2330
+ this.debug("** at the end");
2331
+ for (; fi < fl; fi++) {
2332
+ if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
2333
+ return false;
2334
+ }
2335
+ return true;
2336
+ }
2337
+ while (fr < fl) {
2338
+ var swallowee = file[fr];
2339
+ this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
2340
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
2341
+ this.debug("globstar found match!", fr, fl, swallowee);
2342
+ return true;
2343
+ } else {
2344
+ if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
2345
+ this.debug("dot detected!", file, fr, pattern, pr);
2346
+ break;
2347
+ }
2348
+ this.debug("globstar swallow a segment, and continue");
2349
+ fr++;
2350
+ }
2351
+ }
2352
+ if (partial) {
2353
+ this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
2354
+ if (fr === fl) {
2355
+ return true;
2356
+ }
2357
+ }
2358
+ return false;
2359
+ }
2360
+ let hit;
2361
+ if (typeof p === "string") {
2362
+ hit = f === p;
2363
+ this.debug("string match", p, f, hit);
2364
+ } else {
2365
+ hit = p.test(f);
2366
+ this.debug("pattern match", p, f, hit);
2367
+ }
2368
+ if (!hit)
2369
+ return false;
2370
+ }
2371
+ if (fi === fl && pi === pl) {
2372
+ return true;
2373
+ } else if (fi === fl) {
2374
+ return partial;
2375
+ } else if (pi === pl) {
2376
+ return fi === fl - 1 && file[fi] === "";
2377
+ } else {
2378
+ throw new Error("wtf?");
2379
+ }
2380
+ }
2381
+ braceExpand() {
2382
+ return braceExpand(this.pattern, this.options);
2383
+ }
2384
+ parse(pattern) {
2385
+ assertValidPattern(pattern);
2386
+ const options = this.options;
2387
+ if (pattern === "**")
2388
+ return GLOBSTAR;
2389
+ if (pattern === "")
2390
+ return "";
2391
+ let m;
2392
+ let fastTest = null;
2393
+ if (m = pattern.match(starRE)) {
2394
+ fastTest = options.dot ? starTestDot : starTest;
2395
+ } else if (m = pattern.match(starDotExtRE)) {
2396
+ fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
2397
+ } else if (m = pattern.match(qmarksRE)) {
2398
+ fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
2399
+ } else if (m = pattern.match(starDotStarRE)) {
2400
+ fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
2401
+ } else if (m = pattern.match(dotStarRE)) {
2402
+ fastTest = dotStarTest;
2403
+ }
2404
+ const re = AST.fromGlob(pattern, this.options).toMMPattern();
2405
+ if (fastTest && typeof re === "object") {
2406
+ Reflect.defineProperty(re, "test", { value: fastTest });
2407
+ }
2408
+ return re;
2409
+ }
2410
+ makeRe() {
2411
+ if (this.regexp || this.regexp === false)
2412
+ return this.regexp;
2413
+ const set = this.set;
2414
+ if (!set.length) {
2415
+ this.regexp = false;
2416
+ return this.regexp;
2417
+ }
2418
+ const options = this.options;
2419
+ const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot : twoStarNoDot;
2420
+ const flags = new Set(options.nocase ? ["i"] : []);
2421
+ let re = set.map((pattern) => {
2422
+ const pp = pattern.map((p) => {
2423
+ if (p instanceof RegExp) {
2424
+ for (const f of p.flags.split(""))
2425
+ flags.add(f);
2426
+ }
2427
+ return typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR ? GLOBSTAR : p._src;
2428
+ });
2429
+ pp.forEach((p, i2) => {
2430
+ const next = pp[i2 + 1];
2431
+ const prev = pp[i2 - 1];
2432
+ if (p !== GLOBSTAR || prev === GLOBSTAR) {
2433
+ return;
2434
+ }
2435
+ if (prev === void 0) {
2436
+ if (next !== void 0 && next !== GLOBSTAR) {
2437
+ pp[i2 + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
2438
+ } else {
2439
+ pp[i2] = twoStar;
2440
+ }
2441
+ } else if (next === void 0) {
2442
+ pp[i2 - 1] = prev + "(?:\\/|" + twoStar + ")?";
2443
+ } else if (next !== GLOBSTAR) {
2444
+ pp[i2 - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
2445
+ pp[i2 + 1] = GLOBSTAR;
2446
+ }
2447
+ });
2448
+ return pp.filter((p) => p !== GLOBSTAR).join("/");
2449
+ }).join("|");
2450
+ const [open, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
2451
+ re = "^" + open + re + close + "$";
2452
+ if (this.negate)
2453
+ re = "^(?!" + re + ").+$";
2454
+ try {
2455
+ this.regexp = new RegExp(re, [...flags].join(""));
2456
+ } catch (ex) {
2457
+ this.regexp = false;
2458
+ }
2459
+ return this.regexp;
2460
+ }
2461
+ slashSplit(p) {
2462
+ if (this.preserveMultipleSlashes) {
2463
+ return p.split("/");
2464
+ } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
2465
+ return ["", ...p.split(/\/+/)];
2466
+ } else {
2467
+ return p.split(/\/+/);
2468
+ }
2469
+ }
2470
+ match(f, partial = this.partial) {
2471
+ this.debug("match", f, this.pattern);
2472
+ if (this.comment) {
2473
+ return false;
2474
+ }
2475
+ if (this.empty) {
2476
+ return f === "";
2477
+ }
2478
+ if (f === "/" && partial) {
2479
+ return true;
2480
+ }
2481
+ const options = this.options;
2482
+ if (this.isWindows) {
2483
+ f = f.split("\\").join("/");
2484
+ }
2485
+ const ff = this.slashSplit(f);
2486
+ this.debug(this.pattern, "split", ff);
2487
+ const set = this.set;
2488
+ this.debug(this.pattern, "set", set);
2489
+ let filename = ff[ff.length - 1];
2490
+ if (!filename) {
2491
+ for (let i2 = ff.length - 2; !filename && i2 >= 0; i2--) {
2492
+ filename = ff[i2];
2493
+ }
2494
+ }
2495
+ for (let i2 = 0; i2 < set.length; i2++) {
2496
+ const pattern = set[i2];
2497
+ let file = ff;
2498
+ if (options.matchBase && pattern.length === 1) {
2499
+ file = [filename];
2500
+ }
2501
+ const hit = this.matchOne(file, pattern, partial);
2502
+ if (hit) {
2503
+ if (options.flipNegate) {
2504
+ return true;
2505
+ }
2506
+ return !this.negate;
2507
+ }
2508
+ }
2509
+ if (options.flipNegate) {
2510
+ return false;
2511
+ }
2512
+ return this.negate;
2513
+ }
2514
+ static defaults(def) {
2515
+ return minimatch.defaults(def).Minimatch;
2516
+ }
2517
+ };
2518
+ minimatch.AST = AST;
2519
+ minimatch.Minimatch = Minimatch;
2520
+ minimatch.escape = escape;
2521
+ minimatch.unescape = unescape;
2522
+
2523
+ // src/utils/query-nonce-meta-tag-content.ts
2524
+ function queryNonceMetaTagContent(doc) {
2525
+ var _a, _b, _c;
2526
+ return (_c = (_b = (_a = doc.head) == null ? void 0 : _a.querySelector('meta[name="csp-nonce"]')) == null ? void 0 : _b.getAttribute("content")) != null ? _c : void 0;
2527
+ }
2528
+
2529
+ // src/utils/regular-expression.ts
2530
+ var escapeRegExpSpecialCharacters = (text) => {
2531
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2532
+ };
2533
+
2534
+ // src/utils/result.ts
2535
+ var result_exports = {};
2536
+ __export(result_exports, {
2537
+ err: () => err,
2538
+ map: () => map,
2539
+ ok: () => ok,
2540
+ unwrap: () => unwrap,
2541
+ unwrapErr: () => unwrapErr
2542
+ });
2543
+ var ok = (value) => ({
2544
+ isOk: true,
2545
+ isErr: false,
2546
+ value
2547
+ });
2548
+ var err = (value) => ({
2549
+ isOk: false,
2550
+ isErr: true,
2551
+ value
2552
+ });
2553
+ function map(result, fn) {
2554
+ if (result.isOk) {
2555
+ const val = fn(result.value);
2556
+ if (val instanceof Promise) {
2557
+ return val.then((newVal) => ok(newVal));
2558
+ } else {
2559
+ return ok(val);
2560
+ }
2561
+ }
2562
+ if (result.isErr) {
2563
+ const value = result.value;
2564
+ return err(value);
2565
+ }
2566
+ throw "should never get here";
2567
+ }
2568
+ var unwrap = (result) => {
2569
+ if (result.isOk) {
2570
+ return result.value;
2571
+ } else {
2572
+ throw result.value;
2573
+ }
2574
+ };
2575
+ var unwrapErr = (result) => {
2576
+ if (result.isErr) {
2577
+ return result.value;
2578
+ } else {
2579
+ throw result.value;
2580
+ }
2581
+ };
2582
+
2583
+ // src/utils/style.ts
2584
+ function createStyleSheetIfNeededAndSupported(styles2) {
2585
+ return void 0;
2586
+ }
2587
+
2588
+ // src/utils/shadow-root.ts
2589
+ var globalStyleSheet;
2590
+ function createShadowRoot(cmpMeta) {
2591
+ var _a;
2592
+ const opts = { mode: "open" };
2593
+ const shadowRoot = this.attachShadow(opts);
2594
+ if (globalStyleSheet === void 0) globalStyleSheet = (_a = createStyleSheetIfNeededAndSupported()) != null ? _a : null;
2595
+ if (globalStyleSheet) {
2596
+ if (supportsMutableAdoptedStyleSheets) {
2597
+ shadowRoot.adoptedStyleSheets.push(globalStyleSheet);
2598
+ } else {
2599
+ shadowRoot.adoptedStyleSheets = [...shadowRoot.adoptedStyleSheets, globalStyleSheet];
2600
+ }
2601
+ }
2602
+ }
2603
+ var createTime = (fnName, tagName = "") => {
2604
+ {
2605
+ return () => {
2606
+ return;
2607
+ };
2608
+ }
2609
+ };
2610
+ var uniqueTime = (key, measureText) => {
2611
+ {
2612
+ return () => {
2613
+ return;
2614
+ };
2615
+ }
2616
+ };
2617
+ var rootAppliedStyles = /* @__PURE__ */ new WeakMap();
2618
+ var registerStyle = (scopeId2, cssText, allowCS) => {
2619
+ let style = styles.get(scopeId2);
2620
+ if (supportsConstructableStylesheets && allowCS) {
2621
+ style = style || new CSSStyleSheet();
2622
+ if (typeof style === "string") {
2623
+ style = cssText;
2624
+ } else {
2625
+ style.replaceSync(cssText);
2626
+ }
2627
+ } else {
2628
+ style = cssText;
2629
+ }
2630
+ styles.set(scopeId2, style);
2631
+ };
2632
+ var addStyle = (styleContainerNode, cmpMeta, mode) => {
2633
+ var _a, _b, _c;
2634
+ const scopeId2 = getScopeId(cmpMeta);
2635
+ const style = styles.get(scopeId2);
2636
+ if (!win.document) {
2637
+ return scopeId2;
2638
+ }
2639
+ styleContainerNode = styleContainerNode.nodeType === 11 /* DocumentFragment */ ? styleContainerNode : win.document;
2640
+ if (style) {
2641
+ if (typeof style === "string") {
2642
+ styleContainerNode = styleContainerNode.head || styleContainerNode;
2643
+ let appliedStyles = rootAppliedStyles.get(styleContainerNode);
2644
+ let styleElm;
2645
+ if (!appliedStyles) {
2646
+ rootAppliedStyles.set(styleContainerNode, appliedStyles = /* @__PURE__ */ new Set());
2647
+ }
2648
+ if (!appliedStyles.has(scopeId2)) {
2649
+ styleElm = win.document.createElement("style");
2650
+ styleElm.innerHTML = style;
2651
+ const nonce = (_a = plt.$nonce$) != null ? _a : queryNonceMetaTagContent(win.document);
2652
+ if (nonce != null) {
2653
+ styleElm.setAttribute("nonce", nonce);
2654
+ }
2655
+ if (!(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */)) {
2656
+ if (styleContainerNode.nodeName === "HEAD") {
2657
+ const preconnectLinks = styleContainerNode.querySelectorAll("link[rel=preconnect]");
2658
+ const referenceNode2 = preconnectLinks.length > 0 ? preconnectLinks[preconnectLinks.length - 1].nextSibling : styleContainerNode.querySelector("style");
2659
+ styleContainerNode.insertBefore(
2660
+ styleElm,
2661
+ (referenceNode2 == null ? void 0 : referenceNode2.parentNode) === styleContainerNode ? referenceNode2 : null
2662
+ );
2663
+ } else if ("host" in styleContainerNode) {
2664
+ if (supportsConstructableStylesheets) {
2665
+ const currentWindow = (_b = styleContainerNode.defaultView) != null ? _b : styleContainerNode.ownerDocument.defaultView;
2666
+ const stylesheet = new currentWindow.CSSStyleSheet();
2667
+ stylesheet.replaceSync(style);
2668
+ if (supportsMutableAdoptedStyleSheets) {
2669
+ styleContainerNode.adoptedStyleSheets.unshift(stylesheet);
2670
+ } else {
2671
+ styleContainerNode.adoptedStyleSheets = [stylesheet, ...styleContainerNode.adoptedStyleSheets];
2672
+ }
2673
+ } else {
2674
+ const existingStyleContainer = styleContainerNode.querySelector("style");
2675
+ if (existingStyleContainer) {
2676
+ existingStyleContainer.innerHTML = style + existingStyleContainer.innerHTML;
2677
+ } else {
2678
+ styleContainerNode.prepend(styleElm);
2679
+ }
2680
+ }
2681
+ } else {
2682
+ styleContainerNode.append(styleElm);
2683
+ }
2684
+ }
2685
+ if (cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) {
2686
+ styleContainerNode.insertBefore(styleElm, null);
2687
+ }
2688
+ if (cmpMeta.$flags$ & 4 /* hasSlotRelocation */) {
2689
+ styleElm.innerHTML += SLOT_FB_CSS;
2690
+ }
2691
+ if (appliedStyles) {
2692
+ appliedStyles.add(scopeId2);
2693
+ }
2694
+ }
2695
+ } else {
2696
+ let appliedStyles = rootAppliedStyles.get(styleContainerNode);
2697
+ if (!appliedStyles) {
2698
+ rootAppliedStyles.set(styleContainerNode, appliedStyles = /* @__PURE__ */ new Set());
2699
+ }
2700
+ if (!appliedStyles.has(scopeId2)) {
2701
+ const currentWindow = (_c = styleContainerNode.defaultView) != null ? _c : styleContainerNode.ownerDocument.defaultView;
2702
+ let stylesheet;
2703
+ if (style.constructor === currentWindow.CSSStyleSheet) {
2704
+ stylesheet = style;
2705
+ } else {
2706
+ stylesheet = new currentWindow.CSSStyleSheet();
2707
+ for (let i2 = 0; i2 < style.cssRules.length; i2++) {
2708
+ stylesheet.insertRule(style.cssRules[i2].cssText, i2);
2709
+ }
2710
+ }
2711
+ if (supportsMutableAdoptedStyleSheets) {
2712
+ styleContainerNode.adoptedStyleSheets.push(stylesheet);
2713
+ } else {
2714
+ styleContainerNode.adoptedStyleSheets = [...styleContainerNode.adoptedStyleSheets, stylesheet];
2715
+ }
2716
+ appliedStyles.add(scopeId2);
2717
+ }
2718
+ }
2719
+ }
2720
+ return scopeId2;
2721
+ };
2722
+ var attachStyles = (hostRef) => {
2723
+ const cmpMeta = hostRef.$cmpMeta$;
2724
+ const elm = hostRef.$hostElement$;
2725
+ const flags = cmpMeta.$flags$;
2726
+ const endAttachStyles = createTime("attachStyles", cmpMeta.$tagName$);
2727
+ const scopeId2 = addStyle(
2728
+ elm.shadowRoot ? elm.shadowRoot : elm.getRootNode(),
2729
+ cmpMeta);
2730
+ if (flags & 10 /* needsScopedEncapsulation */) {
2731
+ elm["s-sc"] = scopeId2;
2732
+ elm.classList.add(scopeId2 + "-h");
2733
+ }
2734
+ endAttachStyles();
2735
+ };
2736
+ var getScopeId = (cmp, mode) => "sc-" + (cmp.$tagName$);
2737
+ var h = (nodeName, vnodeData, ...children) => {
2738
+ if (typeof nodeName === "string") {
2739
+ nodeName = transformTag(nodeName);
2740
+ }
2741
+ let child = null;
2742
+ let key = null;
2743
+ let simple = false;
2744
+ let lastSimple = false;
2745
+ const vNodeChildren = [];
2746
+ const walk = (c) => {
2747
+ for (let i2 = 0; i2 < c.length; i2++) {
2748
+ child = c[i2];
2749
+ if (Array.isArray(child)) {
2750
+ walk(child);
2751
+ } else if (child != null && typeof child !== "boolean") {
2752
+ if (simple = typeof nodeName !== "function" && !isComplexType(child)) {
2753
+ child = String(child);
2754
+ }
2755
+ if (simple && lastSimple) {
2756
+ vNodeChildren[vNodeChildren.length - 1].$text$ += child;
2757
+ } else {
2758
+ vNodeChildren.push(simple ? newVNode(null, child) : child);
2759
+ }
2760
+ lastSimple = simple;
2761
+ }
2762
+ }
2763
+ };
2764
+ walk(children);
2765
+ if (vnodeData) {
2766
+ if (vnodeData.key) {
2767
+ key = vnodeData.key;
2768
+ }
2769
+ {
2770
+ const classData = vnodeData.className || vnodeData.class;
2771
+ if (classData) {
2772
+ vnodeData.class = typeof classData !== "object" ? classData : Object.keys(classData).filter((k) => classData[k]).join(" ");
2773
+ }
2774
+ }
2775
+ }
2776
+ const vnode = newVNode(nodeName, null);
2777
+ vnode.$attrs$ = vnodeData;
2778
+ if (vNodeChildren.length > 0) {
2779
+ vnode.$children$ = vNodeChildren;
2780
+ }
2781
+ {
2782
+ vnode.$key$ = key;
2783
+ }
2784
+ return vnode;
2785
+ };
2786
+ var newVNode = (tag, text) => {
2787
+ const vnode = {
2788
+ $flags$: 0,
2789
+ $tag$: tag,
2790
+ $text$: text,
2791
+ $elm$: null,
2792
+ $children$: null
2793
+ };
2794
+ {
2795
+ vnode.$attrs$ = null;
2796
+ }
2797
+ {
2798
+ vnode.$key$ = null;
2799
+ }
2800
+ return vnode;
2801
+ };
2802
+ var Host = {};
2803
+ var isHost = (node) => node && node.$tag$ === Host;
2804
+ var createSupportsRuleRe = (selector) => {
2805
+ const safeSelector2 = escapeRegExpSpecialCharacters(selector);
2806
+ return new RegExp(
2807
+ // First capture group: match any context before the selector that's not inside @supports selector()
2808
+ // Using negative lookahead to avoid matching inside @supports selector(...) condition
2809
+ `(^|[^@]|@(?!supports\\s+selector\\s*\\([^{]*?${safeSelector2}))(${safeSelector2}\\b)`,
2810
+ "g"
2811
+ );
2812
+ };
2813
+ createSupportsRuleRe("::slotted");
2814
+ createSupportsRuleRe(":host");
2815
+ createSupportsRuleRe(":host-context");
2816
+ var parsePropertyValue = (propValue, propType, isFormAssociated) => {
2817
+ if (propValue != null && !isComplexType(propValue)) {
2818
+ if (propType & 4 /* Boolean */) {
2819
+ {
2820
+ return propValue === "false" ? false : propValue === "" || !!propValue;
2821
+ }
2822
+ }
2823
+ if (propType & 1 /* String */) {
2824
+ return String(propValue);
2825
+ }
2826
+ return propValue;
2827
+ }
2828
+ return propValue;
2829
+ };
2830
+ var emitEvent = (elm, name, opts) => {
2831
+ const ev = plt.ce(name, opts);
2832
+ elm.dispatchEvent(ev);
2833
+ return ev;
2834
+ };
2835
+ var setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags, initialRender) => {
2836
+ if (oldValue === newValue) {
2837
+ return;
2838
+ }
2839
+ let isProp = isMemberInElement(elm, memberName);
2840
+ let ln = memberName.toLowerCase();
2841
+ if (memberName === "class") {
2842
+ const classList = elm.classList;
2843
+ const oldClasses = parseClassList(oldValue);
2844
+ let newClasses = parseClassList(newValue);
2845
+ {
2846
+ classList.remove(...oldClasses.filter((c) => c && !newClasses.includes(c)));
2847
+ classList.add(...newClasses.filter((c) => c && !oldClasses.includes(c)));
2848
+ }
2849
+ } else if (memberName === "style") {
2850
+ {
2851
+ for (const prop in oldValue) {
2852
+ if (!newValue || newValue[prop] == null) {
2853
+ if (prop.includes("-")) {
2854
+ elm.style.removeProperty(prop);
2855
+ } else {
2856
+ elm.style[prop] = "";
2857
+ }
2858
+ }
2859
+ }
2860
+ }
2861
+ for (const prop in newValue) {
2862
+ if (!oldValue || newValue[prop] !== oldValue[prop]) {
2863
+ if (prop.includes("-")) {
2864
+ elm.style.setProperty(prop, newValue[prop]);
2865
+ } else {
2866
+ elm.style[prop] = newValue[prop];
2867
+ }
2868
+ }
2869
+ }
2870
+ } else if (memberName === "key") ; else if (memberName === "ref") {
2871
+ if (newValue) {
2872
+ newValue(elm);
2873
+ }
2874
+ } else if ((!isProp ) && memberName[0] === "o" && memberName[1] === "n") {
2875
+ if (memberName[2] === "-") {
2876
+ memberName = memberName.slice(3);
2877
+ } else if (isMemberInElement(win, ln)) {
2878
+ memberName = ln.slice(2);
2879
+ } else {
2880
+ memberName = ln[2] + memberName.slice(3);
2881
+ }
2882
+ if (oldValue || newValue) {
2883
+ const capture = memberName.endsWith(CAPTURE_EVENT_SUFFIX);
2884
+ memberName = memberName.replace(CAPTURE_EVENT_REGEX, "");
2885
+ if (oldValue) {
2886
+ plt.rel(elm, memberName, oldValue, capture);
2887
+ }
2888
+ if (newValue) {
2889
+ plt.ael(elm, memberName, newValue, capture);
2890
+ }
2891
+ }
2892
+ } else {
2893
+ const isComplex = isComplexType(newValue);
2894
+ if ((isProp || isComplex && newValue !== null) && !isSvg) {
2895
+ try {
2896
+ if (!elm.tagName.includes("-")) {
2897
+ const n = newValue == null ? "" : newValue;
2898
+ if (memberName === "list") {
2899
+ isProp = false;
2900
+ } else if (oldValue == null || elm[memberName] != n) {
2901
+ if (typeof elm.__lookupSetter__(memberName) === "function") {
2902
+ elm[memberName] = n;
2903
+ } else {
2904
+ elm.setAttribute(memberName, n);
2905
+ }
2906
+ }
2907
+ } else if (elm[memberName] !== newValue) {
2908
+ elm[memberName] = newValue;
2909
+ }
2910
+ } catch (e) {
2911
+ }
2912
+ }
2913
+ if (newValue == null || newValue === false) {
2914
+ if (newValue !== false || elm.getAttribute(memberName) === "") {
2915
+ {
2916
+ elm.removeAttribute(memberName);
2917
+ }
2918
+ }
2919
+ } else if ((!isProp || flags & 4 /* isHost */ || isSvg) && !isComplex && elm.nodeType === 1 /* ElementNode */) {
2920
+ newValue = newValue === true ? "" : newValue;
2921
+ {
2922
+ elm.setAttribute(memberName, newValue);
2923
+ }
2924
+ }
2925
+ }
2926
+ };
2927
+ var parseClassListRegex = /\s/;
2928
+ var parseClassList = (value) => {
2929
+ if (typeof value === "object" && value && "baseVal" in value) {
2930
+ value = value.baseVal;
2931
+ }
2932
+ if (!value || typeof value !== "string") {
2933
+ return [];
2934
+ }
2935
+ return value.split(parseClassListRegex);
2936
+ };
2937
+ var CAPTURE_EVENT_SUFFIX = "Capture";
2938
+ var CAPTURE_EVENT_REGEX = new RegExp(CAPTURE_EVENT_SUFFIX + "$");
2939
+
2940
+ // src/runtime/vdom/update-element.ts
2941
+ var updateElement = (oldVnode, newVnode, isSvgMode2, isInitialRender) => {
2942
+ const elm = newVnode.$elm$.nodeType === 11 /* DocumentFragment */ && newVnode.$elm$.host ? newVnode.$elm$.host : newVnode.$elm$;
2943
+ const oldVnodeAttrs = oldVnode && oldVnode.$attrs$ || {};
2944
+ const newVnodeAttrs = newVnode.$attrs$ || {};
2945
+ {
2946
+ for (const memberName of sortedAttrNames(Object.keys(oldVnodeAttrs))) {
2947
+ if (!(memberName in newVnodeAttrs)) {
2948
+ setAccessor(
2949
+ elm,
2950
+ memberName,
2951
+ oldVnodeAttrs[memberName],
2952
+ void 0,
2953
+ isSvgMode2,
2954
+ newVnode.$flags$);
2955
+ }
2956
+ }
2957
+ }
2958
+ for (const memberName of sortedAttrNames(Object.keys(newVnodeAttrs))) {
2959
+ setAccessor(
2960
+ elm,
2961
+ memberName,
2962
+ oldVnodeAttrs[memberName],
2963
+ newVnodeAttrs[memberName],
2964
+ isSvgMode2,
2965
+ newVnode.$flags$);
2966
+ }
2967
+ };
2968
+ function sortedAttrNames(attrNames) {
2969
+ return attrNames.includes("ref") ? (
2970
+ // we need to sort these to ensure that `'ref'` is the last attr
2971
+ [...attrNames.filter((attr) => attr !== "ref"), "ref"]
2972
+ ) : (
2973
+ // no need to sort, return the original array
2974
+ attrNames
2975
+ );
2976
+ }
2977
+ var hostTagName;
2978
+ var isSvgMode = false;
2979
+ var createElm = (oldParentVNode, newParentVNode, childIndex) => {
2980
+ const newVNode2 = newParentVNode.$children$[childIndex];
2981
+ let i2 = 0;
2982
+ let elm;
2983
+ let childNode;
2984
+ {
2985
+ if (!isSvgMode) {
2986
+ isSvgMode = newVNode2.$tag$ === "svg";
2987
+ }
2988
+ if (!win.document) {
2989
+ throw new Error(
2990
+ "You are trying to render a Stencil component in an environment that doesn't support the DOM. Make sure to populate the [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window/window) object before rendering a component."
2991
+ );
2992
+ }
2993
+ elm = newVNode2.$elm$ = win.document.createElementNS(
2994
+ isSvgMode ? SVG_NS : HTML_NS,
2995
+ newVNode2.$tag$
2996
+ ) ;
2997
+ if (isSvgMode && newVNode2.$tag$ === "foreignObject") {
2998
+ isSvgMode = false;
2999
+ }
3000
+ {
3001
+ updateElement(null, newVNode2, isSvgMode);
3002
+ }
3003
+ if (newVNode2.$children$) {
3004
+ const appendTarget = newVNode2.$tag$ === "template" ? elm.content : elm;
3005
+ for (i2 = 0; i2 < newVNode2.$children$.length; ++i2) {
3006
+ childNode = createElm(oldParentVNode, newVNode2, i2);
3007
+ if (childNode) {
3008
+ appendTarget.appendChild(childNode);
3009
+ }
3010
+ }
3011
+ }
3012
+ {
3013
+ if (newVNode2.$tag$ === "svg") {
3014
+ isSvgMode = false;
3015
+ } else if (elm.tagName === "foreignObject") {
3016
+ isSvgMode = true;
3017
+ }
3018
+ }
3019
+ }
3020
+ elm["s-hn"] = hostTagName;
3021
+ return elm;
3022
+ };
3023
+ var addVnodes = (parentElm, before, parentVNode, vnodes, startIdx, endIdx) => {
3024
+ let containerElm = parentElm;
3025
+ let childNode;
3026
+ if (containerElm.shadowRoot && containerElm.tagName === hostTagName) {
3027
+ containerElm = containerElm.shadowRoot;
3028
+ }
3029
+ if (parentVNode.$tag$ === "template") {
3030
+ containerElm = containerElm.content;
3031
+ }
3032
+ for (; startIdx <= endIdx; ++startIdx) {
3033
+ if (vnodes[startIdx]) {
3034
+ childNode = createElm(null, parentVNode, startIdx);
3035
+ if (childNode) {
3036
+ vnodes[startIdx].$elm$ = childNode;
3037
+ insertBefore(containerElm, childNode, before);
3038
+ }
3039
+ }
3040
+ }
3041
+ };
3042
+ var removeVnodes = (vnodes, startIdx, endIdx) => {
3043
+ for (let index = startIdx; index <= endIdx; ++index) {
3044
+ const vnode = vnodes[index];
3045
+ if (vnode) {
3046
+ const elm = vnode.$elm$;
3047
+ nullifyVNodeRefs(vnode);
3048
+ if (elm) {
3049
+ elm.remove();
3050
+ }
3051
+ }
3052
+ }
3053
+ };
3054
+ var updateChildren = (parentElm, oldCh, newVNode2, newCh, isInitialRender = false) => {
3055
+ let oldStartIdx = 0;
3056
+ let newStartIdx = 0;
3057
+ let idxInOld = 0;
3058
+ let i2 = 0;
3059
+ let oldEndIdx = oldCh.length - 1;
3060
+ let oldStartVnode = oldCh[0];
3061
+ let oldEndVnode = oldCh[oldEndIdx];
3062
+ let newEndIdx = newCh.length - 1;
3063
+ let newStartVnode = newCh[0];
3064
+ let newEndVnode = newCh[newEndIdx];
3065
+ let node;
3066
+ let elmToMove;
3067
+ const containerElm = newVNode2.$tag$ === "template" ? parentElm.content : parentElm;
3068
+ while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
3069
+ if (oldStartVnode == null) {
3070
+ oldStartVnode = oldCh[++oldStartIdx];
3071
+ } else if (oldEndVnode == null) {
3072
+ oldEndVnode = oldCh[--oldEndIdx];
3073
+ } else if (newStartVnode == null) {
3074
+ newStartVnode = newCh[++newStartIdx];
3075
+ } else if (newEndVnode == null) {
3076
+ newEndVnode = newCh[--newEndIdx];
3077
+ } else if (isSameVnode(oldStartVnode, newStartVnode, isInitialRender)) {
3078
+ patch(oldStartVnode, newStartVnode, isInitialRender);
3079
+ oldStartVnode = oldCh[++oldStartIdx];
3080
+ newStartVnode = newCh[++newStartIdx];
3081
+ } else if (isSameVnode(oldEndVnode, newEndVnode, isInitialRender)) {
3082
+ patch(oldEndVnode, newEndVnode, isInitialRender);
3083
+ oldEndVnode = oldCh[--oldEndIdx];
3084
+ newEndVnode = newCh[--newEndIdx];
3085
+ } else if (isSameVnode(oldStartVnode, newEndVnode, isInitialRender)) {
3086
+ patch(oldStartVnode, newEndVnode, isInitialRender);
3087
+ insertBefore(containerElm, oldStartVnode.$elm$, oldEndVnode.$elm$.nextSibling);
3088
+ oldStartVnode = oldCh[++oldStartIdx];
3089
+ newEndVnode = newCh[--newEndIdx];
3090
+ } else if (isSameVnode(oldEndVnode, newStartVnode, isInitialRender)) {
3091
+ patch(oldEndVnode, newStartVnode, isInitialRender);
3092
+ insertBefore(containerElm, oldEndVnode.$elm$, oldStartVnode.$elm$);
3093
+ oldEndVnode = oldCh[--oldEndIdx];
3094
+ newStartVnode = newCh[++newStartIdx];
3095
+ } else {
3096
+ idxInOld = -1;
3097
+ {
3098
+ for (i2 = oldStartIdx; i2 <= oldEndIdx; ++i2) {
3099
+ if (oldCh[i2] && oldCh[i2].$key$ !== null && oldCh[i2].$key$ === newStartVnode.$key$) {
3100
+ idxInOld = i2;
3101
+ break;
3102
+ }
3103
+ }
3104
+ }
3105
+ if (idxInOld >= 0) {
3106
+ elmToMove = oldCh[idxInOld];
3107
+ if (elmToMove.$tag$ !== newStartVnode.$tag$) {
3108
+ node = createElm(oldCh && oldCh[newStartIdx], newVNode2, idxInOld);
3109
+ } else {
3110
+ patch(elmToMove, newStartVnode, isInitialRender);
3111
+ oldCh[idxInOld] = void 0;
3112
+ node = elmToMove.$elm$;
3113
+ }
3114
+ newStartVnode = newCh[++newStartIdx];
3115
+ } else {
3116
+ node = createElm(oldCh && oldCh[newStartIdx], newVNode2, newStartIdx);
3117
+ newStartVnode = newCh[++newStartIdx];
3118
+ }
3119
+ if (node) {
3120
+ {
3121
+ insertBefore(oldStartVnode.$elm$.parentNode, node, oldStartVnode.$elm$);
3122
+ }
3123
+ }
3124
+ }
3125
+ }
3126
+ if (oldStartIdx > oldEndIdx) {
3127
+ addVnodes(
3128
+ parentElm,
3129
+ newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].$elm$,
3130
+ newVNode2,
3131
+ newCh,
3132
+ newStartIdx,
3133
+ newEndIdx
3134
+ );
3135
+ } else if (newStartIdx > newEndIdx) {
3136
+ removeVnodes(oldCh, oldStartIdx, oldEndIdx);
3137
+ }
3138
+ };
3139
+ var isSameVnode = (leftVNode, rightVNode, isInitialRender = false) => {
3140
+ if (leftVNode.$tag$ === rightVNode.$tag$) {
3141
+ if (!isInitialRender) {
3142
+ return leftVNode.$key$ === rightVNode.$key$;
3143
+ }
3144
+ if (isInitialRender && !leftVNode.$key$ && rightVNode.$key$) {
3145
+ leftVNode.$key$ = rightVNode.$key$;
3146
+ }
3147
+ return true;
3148
+ }
3149
+ return false;
3150
+ };
3151
+ var patch = (oldVNode, newVNode2, isInitialRender = false) => {
3152
+ const elm = newVNode2.$elm$ = oldVNode.$elm$;
3153
+ const oldChildren = oldVNode.$children$;
3154
+ const newChildren = newVNode2.$children$;
3155
+ const tag = newVNode2.$tag$;
3156
+ {
3157
+ {
3158
+ isSvgMode = tag === "svg" ? true : tag === "foreignObject" ? false : isSvgMode;
3159
+ }
3160
+ {
3161
+ updateElement(oldVNode, newVNode2, isSvgMode);
3162
+ }
3163
+ if (oldChildren !== null && newChildren !== null) {
3164
+ updateChildren(elm, oldChildren, newVNode2, newChildren, isInitialRender);
3165
+ } else if (newChildren !== null) {
3166
+ addVnodes(elm, null, newVNode2, newChildren, 0, newChildren.length - 1);
3167
+ } else if (
3168
+ // don't do this on initial render as it can cause non-hydrated content to be removed
3169
+ !isInitialRender && BUILD.updatable && oldChildren !== null
3170
+ ) {
3171
+ removeVnodes(oldChildren, 0, oldChildren.length - 1);
3172
+ } else ;
3173
+ if (isSvgMode && tag === "svg") {
3174
+ isSvgMode = false;
3175
+ }
3176
+ }
3177
+ };
3178
+ var nullifyVNodeRefs = (vNode) => {
3179
+ {
3180
+ vNode.$attrs$ && vNode.$attrs$.ref && vNode.$attrs$.ref(null);
3181
+ vNode.$children$ && vNode.$children$.map(nullifyVNodeRefs);
3182
+ }
3183
+ };
3184
+ var insertBefore = (parent, newNode, reference) => {
3185
+ {
3186
+ return parent == null ? void 0 : parent.insertBefore(newNode, reference);
3187
+ }
3188
+ };
3189
+ var renderVdom = (hostRef, renderFnResults, isInitialLoad = false) => {
3190
+ const hostElm = hostRef.$hostElement$;
3191
+ const oldVNode = hostRef.$vnode$ || newVNode(null, null);
3192
+ const isHostElement = isHost(renderFnResults);
3193
+ const rootVnode = isHostElement ? renderFnResults : h(null, null, renderFnResults);
3194
+ hostTagName = hostElm.tagName;
3195
+ if (isInitialLoad && rootVnode.$attrs$) {
3196
+ for (const key of Object.keys(rootVnode.$attrs$)) {
3197
+ if (hostElm.hasAttribute(key) && !["key", "ref", "style", "class"].includes(key)) {
3198
+ rootVnode.$attrs$[key] = hostElm[key];
3199
+ }
3200
+ }
3201
+ }
3202
+ rootVnode.$tag$ = null;
3203
+ rootVnode.$flags$ |= 4 /* isHost */;
3204
+ hostRef.$vnode$ = rootVnode;
3205
+ rootVnode.$elm$ = oldVNode.$elm$ = hostElm.shadowRoot || hostElm ;
3206
+ patch(oldVNode, rootVnode, isInitialLoad);
3207
+ };
3208
+
3209
+ // src/runtime/update-component.ts
3210
+ var attachToAncestor = (hostRef, ancestorComponent) => {
3211
+ if (ancestorComponent && !hostRef.$onRenderResolve$ && ancestorComponent["s-p"]) {
3212
+ const index = ancestorComponent["s-p"].push(
3213
+ new Promise(
3214
+ (r) => hostRef.$onRenderResolve$ = () => {
3215
+ ancestorComponent["s-p"].splice(index - 1, 1);
3216
+ r();
3217
+ }
3218
+ )
3219
+ );
3220
+ }
3221
+ };
3222
+ var scheduleUpdate = (hostRef, isInitialLoad) => {
3223
+ {
3224
+ hostRef.$flags$ |= 16 /* isQueuedForUpdate */;
3225
+ }
3226
+ if (hostRef.$flags$ & 4 /* isWaitingForChildren */) {
3227
+ hostRef.$flags$ |= 512 /* needsRerender */;
3228
+ return;
3229
+ }
3230
+ attachToAncestor(hostRef, hostRef.$ancestorComponent$);
3231
+ const dispatch = () => dispatchHooks(hostRef, isInitialLoad);
3232
+ if (isInitialLoad) {
3233
+ queueMicrotask(() => {
3234
+ dispatch();
3235
+ });
3236
+ return;
3237
+ }
3238
+ return writeTask(dispatch) ;
3239
+ };
3240
+ var dispatchHooks = (hostRef, isInitialLoad) => {
3241
+ const elm = hostRef.$hostElement$;
3242
+ const endSchedule = createTime("scheduleUpdate", hostRef.$cmpMeta$.$tagName$);
3243
+ const instance = hostRef.$lazyInstance$ ;
3244
+ if (!instance) {
3245
+ throw new Error(
3246
+ `Can't render component <${elm.tagName.toLowerCase()} /> with invalid Stencil runtime! Make sure this imported component is compiled with a \`externalRuntime: true\` flag. For more information, please refer to https://stenciljs.com/docs/custom-elements#externalruntime`
3247
+ );
3248
+ }
3249
+ let maybePromise;
3250
+ if (isInitialLoad) {
3251
+ {
3252
+ if (hostRef.$fetchedCbList$.length) {
3253
+ hostRef.$fetchedCbList$.forEach((cb) => cb(elm));
3254
+ }
3255
+ }
3256
+ maybePromise = safeCall(instance, "componentWillLoad", void 0, elm);
3257
+ } else {
3258
+ maybePromise = safeCall(instance, "componentWillUpdate", void 0, elm);
3259
+ }
3260
+ maybePromise = enqueue(maybePromise, () => safeCall(instance, "componentWillRender", void 0, elm));
3261
+ endSchedule();
3262
+ return enqueue(maybePromise, () => updateComponent(hostRef, instance, isInitialLoad));
3263
+ };
3264
+ var enqueue = (maybePromise, fn) => isPromisey(maybePromise) ? maybePromise.then(fn).catch((err2) => {
3265
+ console.error(err2);
3266
+ fn();
3267
+ }) : fn();
3268
+ var isPromisey = (maybePromise) => maybePromise instanceof Promise || maybePromise && maybePromise.then && typeof maybePromise.then === "function";
3269
+ var updateComponent = async (hostRef, instance, isInitialLoad) => {
3270
+ var _a;
3271
+ const elm = hostRef.$hostElement$;
3272
+ const endUpdate = createTime("update", hostRef.$cmpMeta$.$tagName$);
3273
+ const rc = elm["s-rc"];
3274
+ if (isInitialLoad) {
3275
+ attachStyles(hostRef);
3276
+ }
3277
+ const endRender = createTime("render", hostRef.$cmpMeta$.$tagName$);
3278
+ {
3279
+ callRender(hostRef, instance, elm, isInitialLoad);
3280
+ }
3281
+ if (rc) {
3282
+ rc.map((cb) => cb());
3283
+ elm["s-rc"] = void 0;
3284
+ }
3285
+ endRender();
3286
+ endUpdate();
3287
+ {
3288
+ const childrenPromises = (_a = elm["s-p"]) != null ? _a : [];
3289
+ const postUpdate = () => postUpdateComponent(hostRef);
3290
+ if (childrenPromises.length === 0) {
3291
+ postUpdate();
3292
+ } else {
3293
+ Promise.all(childrenPromises).then(postUpdate);
3294
+ hostRef.$flags$ |= 4 /* isWaitingForChildren */;
3295
+ childrenPromises.length = 0;
3296
+ }
3297
+ }
3298
+ };
3299
+ var callRender = (hostRef, instance, elm, isInitialLoad) => {
3300
+ try {
3301
+ instance = instance.render() ;
3302
+ {
3303
+ hostRef.$flags$ &= -17 /* isQueuedForUpdate */;
3304
+ }
3305
+ {
3306
+ hostRef.$flags$ |= 2 /* hasRendered */;
3307
+ }
3308
+ {
3309
+ {
3310
+ {
3311
+ renderVdom(hostRef, instance, isInitialLoad);
3312
+ }
3313
+ }
3314
+ }
3315
+ } catch (e) {
3316
+ consoleError(e, hostRef.$hostElement$);
3317
+ }
3318
+ return null;
3319
+ };
3320
+ var postUpdateComponent = (hostRef) => {
3321
+ const tagName = hostRef.$cmpMeta$.$tagName$;
3322
+ const elm = hostRef.$hostElement$;
3323
+ const endPostUpdate = createTime("postUpdate", tagName);
3324
+ const instance = hostRef.$lazyInstance$ ;
3325
+ const ancestorComponent = hostRef.$ancestorComponent$;
3326
+ safeCall(instance, "componentDidRender", void 0, elm);
3327
+ if (!(hostRef.$flags$ & 64 /* hasLoadedComponent */)) {
3328
+ hostRef.$flags$ |= 64 /* hasLoadedComponent */;
3329
+ {
3330
+ addHydratedFlag(elm);
3331
+ }
3332
+ safeCall(instance, "componentDidLoad", void 0, elm);
3333
+ endPostUpdate();
3334
+ {
3335
+ hostRef.$onReadyResolve$(elm);
3336
+ if (!ancestorComponent) {
3337
+ appDidLoad();
3338
+ }
3339
+ }
3340
+ } else {
3341
+ safeCall(instance, "componentDidUpdate", void 0, elm);
3342
+ endPostUpdate();
3343
+ }
3344
+ {
3345
+ if (hostRef.$onRenderResolve$) {
3346
+ hostRef.$onRenderResolve$();
3347
+ hostRef.$onRenderResolve$ = void 0;
3348
+ }
3349
+ if (hostRef.$flags$ & 512 /* needsRerender */) {
3350
+ nextTick(() => scheduleUpdate(hostRef, false));
3351
+ }
3352
+ hostRef.$flags$ &= -517;
3353
+ }
3354
+ };
3355
+ var appDidLoad = (who) => {
3356
+ nextTick(() => emitEvent(win, "appload", { detail: { namespace: NAMESPACE } }));
3357
+ };
3358
+ var safeCall = (instance, method, arg, elm) => {
3359
+ if (instance && instance[method]) {
3360
+ try {
3361
+ return instance[method](arg);
3362
+ } catch (e) {
3363
+ consoleError(e, elm);
3364
+ }
3365
+ }
3366
+ return void 0;
3367
+ };
3368
+ var addHydratedFlag = (elm) => {
3369
+ var _a;
3370
+ return elm.classList.add((_a = BUILD.hydratedSelectorName) != null ? _a : "hydrated") ;
3371
+ };
3372
+
3373
+ // src/runtime/set-value.ts
3374
+ var getValue = (ref, propName) => getHostRef(ref).$instanceValues$.get(propName);
3375
+ var setValue = (ref, propName, newVal, cmpMeta) => {
3376
+ const hostRef = getHostRef(ref);
3377
+ if (!hostRef) {
3378
+ return;
3379
+ }
3380
+ if (!hostRef) {
3381
+ throw new Error(
3382
+ `Couldn't find host element for "${cmpMeta.$tagName$}" as it is unknown to this Stencil runtime. This usually happens when integrating a 3rd party Stencil component with another Stencil component or application. Please reach out to the maintainers of the 3rd party Stencil component or report this on the Stencil Discord server (https://chat.stenciljs.com) or comment on this similar [GitHub issue](https://github.com/stenciljs/core/issues/5457).`
3383
+ );
3384
+ }
3385
+ const oldVal = hostRef.$instanceValues$.get(propName);
3386
+ const flags = hostRef.$flags$;
3387
+ const instance = hostRef.$lazyInstance$ ;
3388
+ newVal = parsePropertyValue(
3389
+ newVal,
3390
+ cmpMeta.$members$[propName][0]);
3391
+ const areBothNaN = Number.isNaN(oldVal) && Number.isNaN(newVal);
3392
+ const didValueChange = newVal !== oldVal && !areBothNaN;
3393
+ if ((!(flags & 8 /* isConstructingInstance */) || oldVal === void 0) && didValueChange) {
3394
+ hostRef.$instanceValues$.set(propName, newVal);
3395
+ if ((flags & (2 /* hasRendered */ | 16 /* isQueuedForUpdate */)) === 2 /* hasRendered */) {
3396
+ if (instance.componentShouldUpdate) {
3397
+ if (instance.componentShouldUpdate(newVal, oldVal, propName) === false) {
3398
+ return;
3399
+ }
3400
+ }
3401
+ scheduleUpdate(hostRef, false);
3402
+ }
3403
+ }
3404
+ };
3405
+
3406
+ // src/runtime/proxy-component.ts
3407
+ var proxyComponent = (Cstr, cmpMeta, flags) => {
3408
+ var _a, _b;
3409
+ const prototype = Cstr.prototype;
3410
+ if (cmpMeta.$members$ || BUILD.propChangeCallback) {
3411
+ const members = Object.entries((_a = cmpMeta.$members$) != null ? _a : {});
3412
+ members.map(([memberName, [memberFlags]]) => {
3413
+ if ((memberFlags & 31 /* Prop */ || (flags & 2 /* proxyState */) && memberFlags & 32 /* State */)) {
3414
+ const { get: origGetter, set: origSetter } = Object.getOwnPropertyDescriptor(prototype, memberName) || {};
3415
+ if (origGetter) cmpMeta.$members$[memberName][0] |= 2048 /* Getter */;
3416
+ if (origSetter) cmpMeta.$members$[memberName][0] |= 4096 /* Setter */;
3417
+ if (flags & 1 /* isElementConstructor */ || !origGetter) {
3418
+ Object.defineProperty(prototype, memberName, {
3419
+ get() {
3420
+ {
3421
+ if ((cmpMeta.$members$[memberName][0] & 2048 /* Getter */) === 0) {
3422
+ return getValue(this, memberName);
3423
+ }
3424
+ const ref = getHostRef(this);
3425
+ const instance = ref ? ref.$lazyInstance$ : prototype;
3426
+ if (!instance) return;
3427
+ return instance[memberName];
3428
+ }
3429
+ },
3430
+ configurable: true,
3431
+ enumerable: true
3432
+ });
3433
+ }
3434
+ Object.defineProperty(prototype, memberName, {
3435
+ set(newValue) {
3436
+ const ref = getHostRef(this);
3437
+ if (!ref) {
3438
+ return;
3439
+ }
3440
+ if (origSetter) {
3441
+ const currentValue = memberFlags & 32 /* State */ ? this[memberName] : ref.$hostElement$[memberName];
3442
+ if (typeof currentValue === "undefined" && ref.$instanceValues$.get(memberName)) {
3443
+ newValue = ref.$instanceValues$.get(memberName);
3444
+ }
3445
+ origSetter.apply(this, [
3446
+ parsePropertyValue(
3447
+ newValue,
3448
+ memberFlags)
3449
+ ]);
3450
+ newValue = memberFlags & 32 /* State */ ? this[memberName] : ref.$hostElement$[memberName];
3451
+ setValue(this, memberName, newValue, cmpMeta);
3452
+ return;
3453
+ }
3454
+ {
3455
+ if ((flags & 1 /* isElementConstructor */) === 0 || (cmpMeta.$members$[memberName][0] & 4096 /* Setter */) === 0) {
3456
+ setValue(this, memberName, newValue, cmpMeta);
3457
+ if (flags & 1 /* isElementConstructor */ && !ref.$lazyInstance$) {
3458
+ ref.$fetchedCbList$.push(() => {
3459
+ if (cmpMeta.$members$[memberName][0] & 4096 /* Setter */ && ref.$lazyInstance$[memberName] !== ref.$instanceValues$.get(memberName)) {
3460
+ ref.$lazyInstance$[memberName] = newValue;
3461
+ }
3462
+ });
3463
+ }
3464
+ return;
3465
+ }
3466
+ const setterSetVal = () => {
3467
+ const currentValue = ref.$lazyInstance$[memberName];
3468
+ if (!ref.$instanceValues$.get(memberName) && currentValue) {
3469
+ ref.$instanceValues$.set(memberName, currentValue);
3470
+ }
3471
+ ref.$lazyInstance$[memberName] = parsePropertyValue(
3472
+ newValue,
3473
+ memberFlags);
3474
+ setValue(this, memberName, ref.$lazyInstance$[memberName], cmpMeta);
3475
+ };
3476
+ if (ref.$lazyInstance$) {
3477
+ setterSetVal();
3478
+ } else {
3479
+ ref.$fetchedCbList$.push(() => {
3480
+ setterSetVal();
3481
+ });
3482
+ }
3483
+ }
3484
+ }
3485
+ });
3486
+ }
3487
+ });
3488
+ if ((flags & 1 /* isElementConstructor */)) {
3489
+ const attrNameToPropName = /* @__PURE__ */ new Map();
3490
+ prototype.attributeChangedCallback = function(attrName, oldValue, newValue) {
3491
+ plt.jmp(() => {
3492
+ var _a2;
3493
+ const propName = attrNameToPropName.get(attrName);
3494
+ const hostRef = getHostRef(this);
3495
+ if (this.hasOwnProperty(propName) && BUILD.lazyLoad) {
3496
+ newValue = this[propName];
3497
+ delete this[propName];
3498
+ }
3499
+ if (prototype.hasOwnProperty(propName) && typeof this[propName] === "number" && // cast type to number to avoid TS compiler issues
3500
+ this[propName] == newValue) {
3501
+ return;
3502
+ } else if (propName == null) {
3503
+ const flags2 = hostRef == null ? void 0 : hostRef.$flags$;
3504
+ if (hostRef && flags2 && !(flags2 & 8 /* isConstructingInstance */) && newValue !== oldValue) {
3505
+ const instance = hostRef.$lazyInstance$ ;
3506
+ const entry = (_a2 = cmpMeta.$watchers$) == null ? void 0 : _a2[attrName];
3507
+ entry == null ? void 0 : entry.forEach((watcher) => {
3508
+ const [[watchMethodName, watcherFlags]] = Object.entries(watcher);
3509
+ if (instance[watchMethodName] != null && (flags2 & 128 /* isWatchReady */ || watcherFlags & 1 /* Immediate */)) {
3510
+ instance[watchMethodName].call(instance, newValue, oldValue, attrName);
3511
+ }
3512
+ });
3513
+ }
3514
+ return;
3515
+ }
3516
+ const propFlags = members.find(([m]) => m === propName);
3517
+ if (propFlags && propFlags[1][0] & 4 /* Boolean */) {
3518
+ newValue = newValue === null || newValue === "false" ? false : true;
3519
+ }
3520
+ const propDesc = Object.getOwnPropertyDescriptor(prototype, propName);
3521
+ if (newValue != this[propName] && (!propDesc.get || !!propDesc.set)) {
3522
+ this[propName] = newValue;
3523
+ }
3524
+ });
3525
+ };
3526
+ Cstr.observedAttributes = Array.from(
3527
+ /* @__PURE__ */ new Set([
3528
+ ...Object.keys((_b = cmpMeta.$watchers$) != null ? _b : {}),
3529
+ ...members.filter(([_, m]) => m[0] & 31 /* HasAttribute */).map(([propName, m]) => {
3530
+ const attrName = m[1] || propName;
3531
+ attrNameToPropName.set(attrName, propName);
3532
+ return attrName;
3533
+ })
3534
+ ])
3535
+ );
3536
+ }
3537
+ }
3538
+ return Cstr;
3539
+ };
3540
+
3541
+ // src/runtime/initialize-component.ts
3542
+ var initializeComponent = async (elm, hostRef, cmpMeta, hmrVersionId) => {
3543
+ let Cstr;
3544
+ if ((hostRef.$flags$ & 32 /* hasInitializedComponent */) === 0) {
3545
+ hostRef.$flags$ |= 32 /* hasInitializedComponent */;
3546
+ const bundleId = cmpMeta.$lazyBundleId$;
3547
+ if (bundleId) {
3548
+ const CstrImport = loadModule(cmpMeta, hostRef);
3549
+ if (CstrImport && "then" in CstrImport) {
3550
+ const endLoad = uniqueTime();
3551
+ Cstr = await CstrImport;
3552
+ endLoad();
3553
+ } else {
3554
+ Cstr = CstrImport;
3555
+ }
3556
+ if (!Cstr) {
3557
+ throw new Error(`Constructor for "${cmpMeta.$tagName$}#${hostRef.$modeName$}" was not found`);
3558
+ }
3559
+ if (!Cstr.isProxied) {
3560
+ proxyComponent(Cstr, cmpMeta, 2 /* proxyState */);
3561
+ Cstr.isProxied = true;
3562
+ }
3563
+ const endNewInstance = createTime("createInstance", cmpMeta.$tagName$);
3564
+ {
3565
+ hostRef.$flags$ |= 8 /* isConstructingInstance */;
3566
+ }
3567
+ try {
3568
+ new Cstr(hostRef);
3569
+ } catch (e) {
3570
+ consoleError(e, elm);
3571
+ }
3572
+ {
3573
+ hostRef.$flags$ &= -9 /* isConstructingInstance */;
3574
+ }
3575
+ endNewInstance();
3576
+ fireConnectedCallback(hostRef.$lazyInstance$, elm);
3577
+ } else {
3578
+ Cstr = elm.constructor;
3579
+ const cmpTag = elm.localName;
3580
+ customElements.whenDefined(cmpTag).then(() => hostRef.$flags$ |= 128 /* isWatchReady */);
3581
+ }
3582
+ if (Cstr && Cstr.style) {
3583
+ let style;
3584
+ if (typeof Cstr.style === "string") {
3585
+ style = Cstr.style;
3586
+ }
3587
+ const scopeId2 = getScopeId(cmpMeta);
3588
+ if (!styles.has(scopeId2) || BUILD.hotModuleReplacement) {
3589
+ const endRegisterStyles = createTime("registerStyles", cmpMeta.$tagName$);
3590
+ registerStyle(scopeId2, style, !!(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */));
3591
+ endRegisterStyles();
3592
+ }
3593
+ }
3594
+ }
3595
+ const ancestorComponent = hostRef.$ancestorComponent$;
3596
+ const schedule = () => scheduleUpdate(hostRef, true);
3597
+ if (ancestorComponent && ancestorComponent["s-rc"]) {
3598
+ ancestorComponent["s-rc"].push(schedule);
3599
+ } else {
3600
+ schedule();
3601
+ }
3602
+ };
3603
+ var fireConnectedCallback = (instance, elm) => {
3604
+ {
3605
+ safeCall(instance, "connectedCallback", void 0, elm);
3606
+ }
3607
+ };
3608
+
3609
+ // src/runtime/connected-callback.ts
3610
+ var connectedCallback = (elm) => {
3611
+ if ((plt.$flags$ & 1 /* isTmpDisconnected */) === 0) {
3612
+ const hostRef = getHostRef(elm);
3613
+ if (!hostRef) {
3614
+ return;
3615
+ }
3616
+ const cmpMeta = hostRef.$cmpMeta$;
3617
+ const endConnected = createTime("connectedCallback", cmpMeta.$tagName$);
3618
+ if (!(hostRef.$flags$ & 1 /* hasConnected */)) {
3619
+ hostRef.$flags$ |= 1 /* hasConnected */;
3620
+ {
3621
+ let ancestorComponent = elm;
3622
+ while (ancestorComponent = ancestorComponent.parentNode || ancestorComponent.host) {
3623
+ if (ancestorComponent["s-p"]) {
3624
+ attachToAncestor(hostRef, hostRef.$ancestorComponent$ = ancestorComponent);
3625
+ break;
3626
+ }
3627
+ }
3628
+ }
3629
+ if (cmpMeta.$members$) {
3630
+ Object.entries(cmpMeta.$members$).map(([memberName, [memberFlags]]) => {
3631
+ if (memberFlags & 31 /* Prop */ && memberName in elm && elm[memberName] !== Object.prototype[memberName]) {
3632
+ const value = elm[memberName];
3633
+ delete elm[memberName];
3634
+ elm[memberName] = value;
3635
+ }
3636
+ });
3637
+ }
3638
+ {
3639
+ initializeComponent(elm, hostRef, cmpMeta);
3640
+ }
3641
+ } else {
3642
+ if (hostRef == null ? void 0 : hostRef.$lazyInstance$) {
3643
+ fireConnectedCallback(hostRef.$lazyInstance$, elm);
3644
+ } else if (hostRef == null ? void 0 : hostRef.$onReadyPromise$) {
3645
+ hostRef.$onReadyPromise$.then(() => fireConnectedCallback(hostRef.$lazyInstance$, elm));
3646
+ }
3647
+ }
3648
+ endConnected();
3649
+ }
3650
+ };
3651
+ var disconnectInstance = (instance, elm) => {
3652
+ {
3653
+ safeCall(instance, "disconnectedCallback", void 0, elm || instance);
3654
+ }
3655
+ };
3656
+ var disconnectedCallback = async (elm) => {
3657
+ if ((plt.$flags$ & 1 /* isTmpDisconnected */) === 0) {
3658
+ const hostRef = getHostRef(elm);
3659
+ if (hostRef == null ? void 0 : hostRef.$lazyInstance$) {
3660
+ disconnectInstance(hostRef.$lazyInstance$, elm);
3661
+ } else if (hostRef == null ? void 0 : hostRef.$onReadyPromise$) {
3662
+ hostRef.$onReadyPromise$.then(() => disconnectInstance(hostRef.$lazyInstance$, elm));
3663
+ }
3664
+ }
3665
+ if (rootAppliedStyles.has(elm)) {
3666
+ rootAppliedStyles.delete(elm);
3667
+ }
3668
+ if (elm.shadowRoot && rootAppliedStyles.has(elm.shadowRoot)) {
3669
+ rootAppliedStyles.delete(elm.shadowRoot);
3670
+ }
3671
+ };
3672
+
3673
+ // src/runtime/bootstrap-lazy.ts
3674
+ var bootstrapLazy = (lazyBundles, options = {}) => {
3675
+ var _a;
3676
+ if (!win.document) {
3677
+ console.warn("Stencil: No document found. Skipping bootstrapping lazy components.");
3678
+ return;
3679
+ }
3680
+ const endBootstrap = createTime();
3681
+ const cmpTags = [];
3682
+ const exclude = options.exclude || [];
3683
+ const customElements2 = win.customElements;
3684
+ const head = win.document.head;
3685
+ const metaCharset = /* @__PURE__ */ head.querySelector("meta[charset]");
3686
+ const dataStyles = /* @__PURE__ */ win.document.createElement("style");
3687
+ const deferredConnectedCallbacks = [];
3688
+ let appLoadFallback;
3689
+ let isBootstrapping = true;
3690
+ Object.assign(plt, options);
3691
+ plt.$resourcesUrl$ = new URL(options.resourcesUrl || "./", win.document.baseURI).href;
3692
+ let hasSlotRelocation = false;
3693
+ lazyBundles.map((lazyBundle) => {
3694
+ lazyBundle[1].map((compactMeta) => {
3695
+ const cmpMeta = {
3696
+ $flags$: compactMeta[0],
3697
+ $tagName$: compactMeta[1],
3698
+ $members$: compactMeta[2],
3699
+ $listeners$: compactMeta[3]
3700
+ };
3701
+ if (cmpMeta.$flags$ & 4 /* hasSlotRelocation */) {
3702
+ hasSlotRelocation = true;
3703
+ }
3704
+ {
3705
+ cmpMeta.$members$ = compactMeta[2];
3706
+ }
3707
+ const tagName = transformTag(cmpMeta.$tagName$);
3708
+ const HostElement = class extends HTMLElement {
3709
+ // StencilLazyHost
3710
+ constructor(self) {
3711
+ super(self);
3712
+ this.hasRegisteredEventListeners = false;
3713
+ self = this;
3714
+ registerHost(self, cmpMeta);
3715
+ if (cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) {
3716
+ {
3717
+ if (!self.shadowRoot) {
3718
+ createShadowRoot.call(self, cmpMeta);
3719
+ } else {
3720
+ if (self.shadowRoot.mode !== "open") {
3721
+ throw new Error(
3722
+ `Unable to re-use existing shadow root for ${cmpMeta.$tagName$}! Mode is set to ${self.shadowRoot.mode} but Stencil only supports open shadow roots.`
3723
+ );
3724
+ }
3725
+ }
3726
+ }
3727
+ }
3728
+ }
3729
+ connectedCallback() {
3730
+ const hostRef = getHostRef(this);
3731
+ if (!hostRef) {
3732
+ return;
3733
+ }
3734
+ if (!this.hasRegisteredEventListeners) {
3735
+ this.hasRegisteredEventListeners = true;
3736
+ }
3737
+ if (appLoadFallback) {
3738
+ clearTimeout(appLoadFallback);
3739
+ appLoadFallback = null;
3740
+ }
3741
+ if (isBootstrapping) {
3742
+ deferredConnectedCallbacks.push(this);
3743
+ } else {
3744
+ plt.jmp(() => connectedCallback(this));
3745
+ }
3746
+ }
3747
+ disconnectedCallback() {
3748
+ plt.jmp(() => disconnectedCallback(this));
3749
+ plt.raf(() => {
3750
+ var _a3;
3751
+ const hostRef = getHostRef(this);
3752
+ if (!hostRef) {
3753
+ return;
3754
+ }
3755
+ const i2 = deferredConnectedCallbacks.findIndex((host) => host === this);
3756
+ if (i2 > -1) {
3757
+ deferredConnectedCallbacks.splice(i2, 1);
3758
+ }
3759
+ if (((_a3 = hostRef == null ? void 0 : hostRef.$vnode$) == null ? void 0 : _a3.$elm$) instanceof Node && !hostRef.$vnode$.$elm$.isConnected) {
3760
+ delete hostRef.$vnode$.$elm$;
3761
+ }
3762
+ });
3763
+ }
3764
+ componentOnReady() {
3765
+ var _a3;
3766
+ return (_a3 = getHostRef(this)) == null ? void 0 : _a3.$onReadyPromise$;
3767
+ }
3768
+ };
3769
+ cmpMeta.$lazyBundleId$ = lazyBundle[0];
3770
+ if (!exclude.includes(tagName) && !customElements2.get(tagName)) {
3771
+ cmpTags.push(tagName);
3772
+ customElements2.define(
3773
+ tagName,
3774
+ proxyComponent(HostElement, cmpMeta, 1 /* isElementConstructor */)
3775
+ );
3776
+ }
3777
+ });
3778
+ });
3779
+ if (cmpTags.length > 0) {
3780
+ if (hasSlotRelocation) {
3781
+ dataStyles.textContent += SLOT_FB_CSS;
3782
+ }
3783
+ {
3784
+ dataStyles.textContent += cmpTags.sort() + HYDRATED_CSS;
3785
+ }
3786
+ if (dataStyles.innerHTML.length) {
3787
+ dataStyles.setAttribute("data-styles", "");
3788
+ const nonce = (_a = plt.$nonce$) != null ? _a : queryNonceMetaTagContent(win.document);
3789
+ if (nonce != null) {
3790
+ dataStyles.setAttribute("nonce", nonce);
3791
+ }
3792
+ head.insertBefore(dataStyles, metaCharset ? metaCharset.nextSibling : head.firstChild);
3793
+ }
3794
+ }
3795
+ isBootstrapping = false;
3796
+ if (deferredConnectedCallbacks.length) {
3797
+ deferredConnectedCallbacks.map((host) => host.connectedCallback());
3798
+ } else {
3799
+ {
3800
+ plt.jmp(() => appLoadFallback = setTimeout(appDidLoad, 30));
3801
+ }
3802
+ }
3803
+ endBootstrap();
3804
+ };
3805
+
3806
+ // src/runtime/nonce.ts
3807
+ var setNonce = (nonce) => plt.$nonce$ = nonce;
3808
+ function transformTag(tag) {
3809
+ return tag;
3810
+ }
3811
+
3812
+ const globalScripts = () => {};
3813
+
3814
+ const defineCustomElements = async (win, options) => {
3815
+ if (typeof window === 'undefined') return undefined;
3816
+ await globalScripts();
3817
+ return bootstrapLazy([["ocr-file-uploader",[[1,"ocr-file-uploader",{"batch":[4],"callback":[16],"jsonSchema":[1,"json-schema"]}]]]], options);
3818
+ };
3819
+
3820
+ (function(){if("undefined"!==typeof window&&void 0!==window.Reflect&&void 0!==window.customElements){var a=HTMLElement;window.HTMLElement=function(){return Reflect.construct(a,[],this.constructor)};HTMLElement.prototype=a.prototype;HTMLElement.prototype.constructor=HTMLElement;Object.setPrototypeOf(HTMLElement,a);}})();
3821
+
3822
+ const voiceInputModuleCss = ":host{display:block;font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif}.row-audio-area{display:flex;flex-direction:row}.voice-recorder-container{display:flex;flex-direction:column;align-items:center;gap:1rem;padding:1rem;border:1px solid #e5e7eb;border-radius:0.5rem;background:#ffffff;max-width:100px;margin:0 auto}.voice-recorder-container-debug{display:flex;flex-direction:column;align-items:center;gap:1rem;padding:1rem;border:1px solid #e5e7eb;border-radius:0.5rem;background:#ffffff;max-width:800px;margin:0 auto}.upload-record-container{display:inline-block;cursor:pointer;width:50px;height:50px}.upload-record-button{display:flex;align-items:center;justify-content:center;transition:transform 0.2s ease, box-shadow 0.2s ease;user-select:none}.upload-record-button svg{width:50px;height:50px;stroke:#4444ee}.upload-record-button svg path{fill:#4444ee}.upload-record-button:hover svg{transform:scale(1.05);stroke:#4444ee}.record-button{display:flex;align-items:center;justify-content:center;width:50px;height:50px;border:none;border-radius:50%;background:#ee4444;color:white;cursor:pointer;transition:all 0.2s ease;position:relative;overflow:hidden}.record-button:hover:not(:disabled){background:#dd3333;transform:scale(1.05)}.record-button:disabled{opacity:0.6;cursor:not-allowed}.record-button.recording{background:#dd3333;animation:pulse 1.5s infinite}.record-button.processing{background:#3b82f6}@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(239, 68, 68, 0.7)}70%{box-shadow:0 0 0 10px rgba(239, 68, 68, 0)}100%{box-shadow:0 0 0 0 rgba(239, 68, 68, 0)}}.record-icon{width:24px;height:24px;fill:currentColor}.status-text{font-size:0.875rem;color:#6b7280;text-align:center;min-height:1.25rem}.status-text.error{color:#ee4444}.status-text.success{color:#10b981}.debug-panel{width:100%;margin-top:1rem;padding:1rem;background:#f9fafb;border:1px solid #e5e7eb;border-radius:0.375rem;font-family:'Monaco', 'Menlo', 'Ubuntu Mono', monospace;font-size:0.75rem}.debug-title{font-weight:600;margin-bottom:0.5rem;color:#374151}.debug-content{white-space:pre-wrap;word-break:break-word;color:#6b7280;max-height:200px;overflow-y:auto}.permissions-warning{padding:0.75rem;background:#fef3c7;border:1px solid #f59e0b;border-radius:0.375rem;color:#92400e;font-size:0.875rem;text-align:center}.form-preview{width:100%;margin-top:1rem;padding:1rem;background:#f8fafc;border:1px solid #e2e8f0;border-radius:0.375rem}.form-preview-title{font-weight:600;margin-bottom:0.5rem;color:#1e293b}.form-field{margin-bottom:0.5rem;font-size:0.875rem}.field-name{font-weight:500;color:#475569}.field-value{color:#64748b;margin-left:0.5rem}.field-value.filled{color:#059669;font-weight:500}.voice-filled-form{display:flex;flex-direction:column;gap:1rem;margin-top:1rem}.form-group{display:flex;flex-direction:column;gap:0.25rem}.form-label{font-weight:500;color:#374151;font-size:0.875rem}.required{color:#ee4444;margin-left:0.125rem}.form-input{padding:0.5rem;border:1px solid #d1d5db;border-radius:0.375rem;font-size:0.875rem;transition:border-color 0.2s ease}.form-input:focus{outline:none;border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59, 130, 246, 0.1)}.form-checkbox{width:auto;padding:0;margin:0}select.form-input{background-color:white;cursor:pointer}input[type=\"date\"].form-input{cursor:pointer}.readonly-select{background:#f9fafb;border:1px solid #d1d5db;border-radius:0.375rem;padding:0.5rem}.select-placeholder{font-size:0.875rem;color:#6b7280;margin-bottom:0.5rem}.select-options-list{list-style:none;margin:0;padding:0;display:flex;flex-wrap:wrap;gap:0.25rem}.select-option{background:#e5e7eb;padding:0.25rem 0.5rem;border-radius:0.25rem;font-size:0.875rem;color:#374151}.multiselect-container{display:flex;flex-direction:column;gap:0.5rem;padding:0.5rem;border:1px solid #d1d5db;border-radius:0.375rem;background:white}.multiselect-option{display:flex;align-items:center;gap:0.5rem;padding:0.5rem;border-radius:0.25rem;cursor:pointer;transition:background 0.2s ease}.multiselect-option:hover{background:#f3f4f6}.multiselect-option input[type=\"checkbox\"]{width:18px;height:18px;cursor:pointer}.multiselect-option input[type=\"checkbox\"]:checked+.multiselect-label{font-weight:600;color:#059669}.multiselect-label{font-size:0.875rem;color:#374151;user-select:none}";
3823
+
3824
+ // Initialize OCR
3825
+ defineCustomElements();
3826
+ const VoiceFormRecorder = class {
3827
+ get parsedInputTypes() {
3828
+ if (!this.inputTypes)
3829
+ return [];
3830
+ try {
3831
+ return JSON.parse(this.inputTypes.replace(/'/g, '"'));
3832
+ }
3833
+ catch (_a) {
3834
+ return this.inputTypes.split(',').map(type => type.trim());
3835
+ }
3836
+ }
3837
+ constructor(hostRef) {
3838
+ registerInstance$1(this, hostRef);
3839
+ this.formFilled = createEvent(this, "formFilled", 7);
3840
+ this.recordingStateChanged = createEvent(this, "recordingStateChanged", 7);
3841
+ this.formJson = '{}';
3842
+ this.serviceConfig = '{}';
3843
+ this.context = undefined;
3844
+ this.classificationRootUrl = 'http://localhost';
3845
+ this.language = 'en';
3846
+ this.inputTypes = '';
3847
+ this.debug = false;
3848
+ this.renderForm = false;
3849
+ this.displayStatus = false;
3850
+ this.isRecording = false;
3851
+ this.isProcessing = false;
3852
+ this.hasError = false;
3853
+ this.transcription = '';
3854
+ this.filledData = null;
3855
+ this.debugInfo = {};
3856
+ this.isReadonlyMode = true; // Start in readonly preview mode
3857
+ this.triggerAudioRecordUpload = () => {
3858
+ this.fileInputAudioRecord.click();
3859
+ };
3860
+ this.handleAudioRecordChange = async (event) => {
3861
+ const input = event.target;
3862
+ if (!input.files || input.files.length === 0)
3863
+ return;
3864
+ const file = input.files[0];
3865
+ // Here you can handle the file upload to your API
3866
+ console.log('Selected file:', file);
3867
+ this.processAudioContent(file);
3868
+ };
3869
+ this.audioRecorder = new AudioRecorderService();
3870
+ }
3871
+ componentWillLoad() {
3872
+ this.initializeServices();
3873
+ }
3874
+ initializeServices() {
3875
+ try {
3876
+ if (!this.context) {
3877
+ this.hasError = true;
3878
+ const errorMessage = (this.language == 'en' ? `Initialization error: context is '${this.context}'` : `Erreur d'initialisation: le contexte est '${this.context}'`);
3879
+ this.statusMessage = errorMessage;
3880
+ this.updateDebugInfo(errorMessage, { error: errorMessage });
3881
+ }
3882
+ else {
3883
+ // Parse form schema
3884
+ this.parsedSchema = JSON.parse(this.formJson || '{}');
3885
+ // Parse service configuration
3886
+ this.parsedConfig = JSON.parse(this.serviceConfig || '{}');
3887
+ // Add API key to config if provided via prop
3888
+ if (this.apiKey) {
3889
+ this.parsedConfig = Object.assign(Object.assign({}, this.parsedConfig), { speechToText: Object.assign(Object.assign({}, this.parsedConfig.speechToText), { apiKey: this.apiKey }), llm: Object.assign(Object.assign({}, this.parsedConfig.llm), { apiKey: this.apiKey }) });
3890
+ }
3891
+ // Initialize services
3892
+ this.speechToTextService = SpeechToTextServiceFactory.create(this.parsedConfig);
3893
+ this.llmService = LLMServiceFactory.create(this.parsedConfig);
3894
+ this.updateDebugInfo('Initialized', {
3895
+ schema: this.parsedSchema,
3896
+ config: this.parsedConfig
3897
+ });
3898
+ this.hasError = false;
3899
+ this.statusMessage = (this.language == 'en' ? 'Select an input method' : 'Sélectionner une méthode de saisie');
3900
+ if (this.parsedInputTypes.length === 0) {
3901
+ this.inputTypes = 'voice';
3902
+ }
3903
+ }
3904
+ }
3905
+ catch (error) {
3906
+ this.hasError = true;
3907
+ this.statusMessage = (this.language == 'en' ? `Initialization error: ${error.message}` : `Erreur d'initialisation: ${error.message}`);
3908
+ this.updateDebugInfo('Initialization Error', { error: error.message });
3909
+ }
3910
+ }
3911
+ updateDebugInfo(action, data) {
3912
+ if (this.debug) {
3913
+ this.debugInfo = Object.assign(Object.assign({}, this.debugInfo), { [action]: {
3914
+ timestamp: new Date().toISOString(),
3915
+ data
3916
+ } });
3917
+ }
3918
+ }
3919
+ async handleRecordClick() {
3920
+ if (this.isProcessing)
3921
+ return;
3922
+ if (this.isRecording) {
3923
+ await this.stopRecordingAndProcess();
3924
+ }
3925
+ else {
3926
+ await this.startRecording();
3927
+ }
3928
+ }
3929
+ async startRecording() {
3930
+ try {
3931
+ this.hasError = false;
3932
+ this.statusMessage = (this.language == 'en' ? 'Starting recording...' : `Enregistrement ...`);
3933
+ this.updateDebugInfo('Start Recording Attempt', {});
3934
+ await this.audioRecorder.startRecording();
3935
+ this.isRecording = true;
3936
+ this.statusMessage = (this.language == 'en' ? 'Recording... Click to stop' : 'Enregistrement ... Cliquer pour stopper');
3937
+ this.updateDebugInfo('Recording Started', {});
3938
+ this.recordingStateChanged.emit({
3939
+ isRecording: true,
3940
+ state: 'recording'
3941
+ });
3942
+ }
3943
+ catch (error) {
3944
+ this.hasError = true;
3945
+ this.statusMessage = (this.language == 'en' ? `Recording failed: ${error.message}` : `Echec de l'enregistrement : ${error.message}`);
3946
+ this.updateDebugInfo('Recording Error', { error: error.message });
3947
+ this.formFilled.emit({
3948
+ success: false,
3949
+ error: error.message
3950
+ });
3951
+ }
3952
+ }
3953
+ async processJsonForm(ocrData) {
3954
+ console.log("processJsonForm", ocrData);
3955
+ try {
3956
+ this.isProcessing = true;
3957
+ this.statusMessage = (this.language == 'en' ? 'Processing json...' : `Traitement du json ...`);
3958
+ // Extract content from OCR format
3959
+ const extractedData = (ocrData === null || ocrData === void 0 ? void 0 : ocrData.content) || ocrData;
3960
+ const jsonForm = JSON.stringify(extractedData);
3961
+ // Fill form using LLM
3962
+ this.statusMessage = (this.language == 'en' ? 'Filling form fields...' : 'Remplissage du formulaire ...');
3963
+ const trimmedSchema = await this.trimSchemaForAI(this.parsedSchema);
3964
+ const filledSchema = await this.llmService.fillFormFromJson(jsonForm, trimmedSchema);
3965
+ // Extract filled data
3966
+ this.filledData = this.extractFilledData(filledSchema);
3967
+ this.updateDebugInfo('Form Filled', {
3968
+ filledSchema,
3969
+ extractedData: this.filledData
3970
+ });
3971
+ this.parsedSchema = this.filledData;
3972
+ this.statusMessage = (this.language == 'en' ? 'Form completed!' : 'Formulaire remplis !');
3973
+ this.hasError = false;
3974
+ // Emit success event
3975
+ this.formFilled.emit({
3976
+ success: true,
3977
+ data: this.filledData,
3978
+ jsonForm: jsonForm
3979
+ });
3980
+ }
3981
+ catch (error) {
3982
+ this.hasError = true;
3983
+ this.statusMessage = (this.language == 'en' ? `Processing failed: ${error.message}` : `Erreur de traitement : ${error.message}`);
3984
+ this.formFilled.emit({
3985
+ success: false,
3986
+ error: error.message,
3987
+ jsonForm: JSON.stringify(ocrData)
3988
+ });
3989
+ }
3990
+ finally {
3991
+ this.isProcessing = false;
3992
+ }
3993
+ }
3994
+ async processAudioContent(audioFile) {
3995
+ this.updateDebugInfo('Audio Captured', {
3996
+ size: audioFile.size,
3997
+ type: audioFile.type
3998
+ });
3999
+ // Transcribe audio
4000
+ this.statusMessage = (this.language == 'en' ? 'Transcribing speech...' : 'Transcription du texte ...');
4001
+ const transcription = await this.speechToTextService.transcribe(audioFile, this.language);
4002
+ this.transcription = transcription;
4003
+ this.updateDebugInfo('Transcription Complete', { transcription });
4004
+ if (!transcription.trim()) {
4005
+ throw new Error('No speech detected in the recording');
4006
+ }
4007
+ // Fill form using LLM
4008
+ this.statusMessage = (this.language == 'en' ? 'Filling form fields...' : 'Remplissage du formulaire ...');
4009
+ const trimmedSchema = await this.trimSchemaForAI(this.parsedSchema);
4010
+ const filledSchema = await this.llmService.fillFormFromTranscription(transcription, trimmedSchema);
4011
+ // Extract filled data
4012
+ this.filledData = this.extractFilledData(filledSchema);
4013
+ this.updateDebugInfo('Form Filled', {
4014
+ filledSchema,
4015
+ extractedData: this.filledData
4016
+ });
4017
+ this.parsedSchema = this.filledData;
4018
+ this.statusMessage = (this.language == 'en' ? 'Form completed!' : 'Formulaire remplis !');
4019
+ this.hasError = false;
4020
+ // Emit success event
4021
+ this.formFilled.emit({
4022
+ success: true,
4023
+ data: this.filledData,
4024
+ transcription: transcription
4025
+ });
4026
+ }
4027
+ async stopRecordingAndProcess() {
4028
+ try {
4029
+ this.isRecording = false;
4030
+ this.isProcessing = true;
4031
+ this.statusMessage = (this.language == 'en' ? 'Processing audio...' : `Traitement de l'audio ...`);
4032
+ this.updateDebugInfo('Stop Recording', {});
4033
+ this.recordingStateChanged.emit({
4034
+ isRecording: false,
4035
+ state: 'processing'
4036
+ });
4037
+ // Stop recording and get audio blob
4038
+ const audioBlob = await this.audioRecorder.stopRecording();
4039
+ const audioContent = new File([audioBlob], 'audio.webm', { type: 'audio/webm' });
4040
+ this.processAudioContent(audioContent);
4041
+ }
4042
+ catch (error) {
4043
+ this.hasError = true;
4044
+ this.statusMessage = (this.language == 'en' ? `Processing failed: ${error.message}` : `Erreur de traitement : ${error.message}`);
4045
+ this.updateDebugInfo('Processing Error', { error: error.message });
4046
+ this.formFilled.emit({
4047
+ success: false,
4048
+ error: error.message,
4049
+ transcription: this.transcription
4050
+ });
4051
+ }
4052
+ finally {
4053
+ this.isProcessing = false;
4054
+ this.recordingStateChanged.emit({
4055
+ isRecording: false,
4056
+ state: 'idle'
4057
+ });
4058
+ }
4059
+ }
4060
+ extractFilledData(filledData) {
4061
+ // console.log("extractFilledData", filledData);
4062
+ const updatedSchema = JSON.parse(JSON.stringify(this.parsedSchema));
4063
+ switch (this.context) {
4064
+ case "ecoteka":
4065
+ // console.log("TODO extractFilledData", filledData);
4066
+ case "ng":
4067
+ if (filledData === null || filledData === void 0 ? void 0 : filledData.fields) {
4068
+ // Map AI response back to original schema structure
4069
+ filledData.fields.forEach((field) => {
4070
+ const originalField = updatedSchema.Children.find((child) => { var _a; return child.System_Name === field.name || ((_a = child.Settings) === null || _a === void 0 ? void 0 : _a.Label) === field.name; });
4071
+ if (originalField && field.value !== undefined && field.value !== null && field.value !== '') {
4072
+ if (!originalField.Settings)
4073
+ originalField.Settings = {};
4074
+ originalField.Settings.Default_Value = field.value;
4075
+ }
4076
+ });
4077
+ }
4078
+ break;
4079
+ case "ecoll-veto":
4080
+ // console.log("TODO extractFilledData", filledData, updatedSchema);
4081
+ if (filledData === null || filledData === void 0 ? void 0 : filledData.fields) {
4082
+ // Map AI response back to original schema structure
4083
+ filledData.fields.forEach((field) => {
4084
+ let originalField = updatedSchema[0].items.find((child) => child.label === field.name);
4085
+ if (!originalField)
4086
+ originalField = updatedSchema[1].items.find((child) => child.label === field.name);
4087
+ if (originalField && field.value !== undefined && field.value !== null && field.value !== '') {
4088
+ updatedSchema[2][originalField.name] = field.value;
4089
+ }
4090
+ });
4091
+ }
4092
+ break;
4093
+ case "track":
4094
+ default:
4095
+ const data = {};
4096
+ Object.entries(filledData.fields).forEach(([fieldID, field]) => {
4097
+ if (field.default !== undefined && field.default !== null && field.default !== '') {
4098
+ updatedSchema[fieldID] = field.default;
4099
+ }
4100
+ if (field.value !== undefined && field.value !== null && field.value !== '') {
4101
+ for (const key in updatedSchema.fields) {
4102
+ const schemaField = updatedSchema.fields[key];
4103
+ if (schemaField.title === field.name) {
4104
+ schemaField.value = field.value || field.default;
4105
+ schemaField.default = field.value || field.default;
4106
+ break; // stop after finding the first match
4107
+ }
4108
+ }
4109
+ }
4110
+ });
4111
+ break;
4112
+ }
4113
+ // console.log("extractFilledData result", updatedSchema);
4114
+ return updatedSchema;
4115
+ }
4116
+ async trimSchemaForAI(schema) {
4117
+ var _a, _b;
4118
+ // console.log("trimSchemaForAI", schema);
4119
+ switch (this.context) {
4120
+ case "ecoteka":
4121
+ // console.log("TODO trimSchemaForAI", schema)
4122
+ case "ng":
4123
+ const trimmed = { fields: [] };
4124
+ schema.Children.forEach((child) => {
4125
+ var _a;
4126
+ if (!child.System_Name || !child.Type)
4127
+ return;
4128
+ const fieldData = {
4129
+ name: child.Label || ((_a = child.Settings) === null || _a === void 0 ? void 0 : _a.Label) || child.System_Name,
4130
+ type: this.mapFieldType(child.Type)
4131
+ };
4132
+ // Add options for classification/select fields
4133
+ const selectTypes = ['InputClassification', 'select'];
4134
+ if (selectTypes.includes(child.Type) && child.Children && child.Children.length > 0) {
4135
+ fieldData.options = child.Children.map((option) => option.System_Name || option.Label || option.toString());
4136
+ }
4137
+ console.log("fieldData", fieldData);
4138
+ trimmed.fields.push(fieldData);
4139
+ });
4140
+ // console.log("Schema apres transformation, contexte NG:", trimmed);
4141
+ return trimmed;
4142
+ case "ecoll-veto":
4143
+ // console.log("TODO trimSchemaForAI", schema)
4144
+ const mergedItemsSchema = (this.parsedSchema[0].items).concat(this.parsedSchema[1].items);
4145
+ if (mergedItemsSchema) {
4146
+ const trimmedSchema = {
4147
+ title: 'Form Name',
4148
+ description: 'Form Description',
4149
+ schema: {}
4150
+ };
4151
+ Object.entries(mergedItemsSchema).forEach(async ([key, field]) => {
4152
+ const fieldName = field.name;
4153
+ const fieldType = this.mapFieldType(field.type);
4154
+ const fieldLabel = field.label || fieldName;
4155
+ const isRequired = field.required || false;
4156
+ const fieldValue = ''; //TODO
4157
+ if (['position', 'thesaurus'].includes(fieldType)) {
4158
+ try {
4159
+ const response = await fetch(`${this.classificationRootUrl}/ng/api/v1/classification/getList/${fieldType.toLowerCase() == 'position' ? "Position" : "Thesaurus"}/?StartNodeID=${field.config.options.options.startNode}`);
4160
+ if (!response.ok)
4161
+ throw new Error(`HTTP error! status: ${response.status}`);
4162
+ const data = await response.json();
4163
+ if (Array.isArray(data)) {
4164
+ const options = data.map(item => ({
4165
+ value: item.ID,
4166
+ label: item.System_Name
4167
+ }));
4168
+ if (options.length > 0) {
4169
+ field.pickerOptions = options;
4170
+ // TODO on degage les quotes simples temporairement, a corriger
4171
+ field.options = options.map(option => option.label.replace("'", ""));
4172
+ }
4173
+ }
4174
+ else {
4175
+ console.error("Unexpected API response format:", data);
4176
+ }
4177
+ }
4178
+ catch (error) {
4179
+ console.error("Error fetching classification data:", error);
4180
+ }
4181
+ }
4182
+ trimmedSchema.schema[fieldName] = {
4183
+ type: fieldType,
4184
+ title: fieldLabel,
4185
+ options: field.options,
4186
+ readonly: field.readonly === true,
4187
+ default: '',
4188
+ };
4189
+ });
4190
+ // console.log("Schema apres transformation, contexte Track:", trimmedSchema);
4191
+ return trimmedSchema;
4192
+ }
4193
+ case "track":
4194
+ default:
4195
+ // Handle simple schema format (backward compatibility)
4196
+ if ((_a = schema === null || schema === void 0 ? void 0 : schema.schema) !== null && _a !== void 0 ? _a : schema === null || schema === void 0 ? void 0 : schema.fields) {
4197
+ const trimmedSchema = {
4198
+ title: schema.title,
4199
+ description: schema.description,
4200
+ schema: {}
4201
+ };
4202
+ const finalSchema = (_b = schema === null || schema === void 0 ? void 0 : schema.schema) !== null && _b !== void 0 ? _b : schema === null || schema === void 0 ? void 0 : schema.fields;
4203
+ Object.entries(finalSchema).forEach(([fieldName, field]) => {
4204
+ trimmedSchema.schema[fieldName] = {
4205
+ type: field.type,
4206
+ title: field.title,
4207
+ options: field.options,
4208
+ readonly: field.Enabled === false,
4209
+ default: field.DefaultValue,
4210
+ pattern: field.Mask,
4211
+ min: field.ValidationMin,
4212
+ max: field.ValidationMax
4213
+ };
4214
+ });
4215
+ // console.log("Schema apres transformation, contexte Track:", trimmedSchema);
4216
+ return trimmedSchema;
4217
+ }
4218
+ break;
4219
+ }
4220
+ return schema;
4221
+ }
4222
+ mapFieldType(type) {
4223
+ const typeMapping = {
4224
+ 'InputAutocomplete': 'string',
4225
+ 'InputInteger': 'number',
4226
+ 'InputTextArea': 'string',
4227
+ 'InputDateTimePicker': 'datetime',
4228
+ 'InputDecimal': 'number',
4229
+ 'InputClassification': 'classification',
4230
+ 'InputCheckbox': 'boolean',
4231
+ 'InputTextTranslation': 'string',
4232
+ 'InputMultiSelect': 'multiselect',
4233
+ 'thesaurus': 'thesaurus',
4234
+ 'position': 'position',
4235
+ 'text': 'string',
4236
+ 'textarea': 'string',
4237
+ 'number': 'number',
4238
+ 'date': 'date',
4239
+ 'datetime': 'datetime',
4240
+ 'select': 'select',
4241
+ 'multiselect': 'multiselect',
4242
+ 'checkbox': 'checkbox'
4243
+ };
4244
+ return typeMapping[type] || 'string';
4245
+ }
4246
+ // Utility methods exposed as public API
4247
+ async convertXmlToJson(xmlForm) {
4248
+ return SchemaConverter.convertXmlToJson(xmlForm, this.classificationRootUrl, this.language);
4249
+ }
4250
+ async convertJsonToXml(jsonForm) {
4251
+ return SchemaConverter.convertJsonToXml(jsonForm);
4252
+ }
4253
+ // Utility methods exposed as public API
4254
+ async convertXmlToJsonLegacy(xmlForm) {
4255
+ return SchemaConverter.convertXmlToJsonLegacy(xmlForm);
4256
+ }
4257
+ async convertJsonToXmlLegacy(jsonForm) {
4258
+ return SchemaConverter.convertJsonToXmlLegacy(jsonForm);
4259
+ }
4260
+ renderUploadButton() {
4261
+ if (!this.parsedInputTypes.includes('ocr'))
4262
+ return;
4263
+ return (h$1("ocr-file-uploader", { batch: false, "json-schema": this.convertSchemaToOcrFormat(this.parsedSchema), callback: (data) => { this.processJsonForm(data); } }));
4264
+ }
4265
+ convertSchemaToOcrFormat(schema) {
4266
+ const ocrSchema = {
4267
+ type: "object",
4268
+ additionalProperties: false,
4269
+ properties: {
4270
+ meta: {
4271
+ type: "object",
4272
+ additionalProperties: false,
4273
+ properties: {
4274
+ page: { type: "integer" },
4275
+ confiance_global: { type: "number" }
4276
+ },
4277
+ required: ["page", "confiance_global"]
4278
+ },
4279
+ content: {
4280
+ type: "object",
4281
+ additionalProperties: false,
4282
+ properties: {},
4283
+ required: []
4284
+ }
4285
+ },
4286
+ required: ["meta", "content"]
4287
+ };
4288
+ if (schema === null || schema === void 0 ? void 0 : schema.Children) {
4289
+ schema.Children.forEach((child) => {
4290
+ var _a;
4291
+ if (child.System_Name && child.Type) {
4292
+ const fieldLabel = ((_a = child.Settings) === null || _a === void 0 ? void 0 : _a.Label) || child.System_Name;
4293
+ const fieldType = this.mapOcrFieldType(child.Type);
4294
+ ocrSchema.properties.content.properties[fieldLabel] = {
4295
+ anyOf: [{ type: fieldType }, { type: "null" }]
4296
+ };
4297
+ }
4298
+ });
4299
+ }
4300
+ return JSON.stringify(ocrSchema);
4301
+ }
4302
+ mapOcrFieldType(type) {
4303
+ const typeMapping = {
4304
+ 'InputInteger': 'number',
4305
+ 'InputDecimal': 'number',
4306
+ 'InputDateTimePicker': 'string',
4307
+ 'InputCheckbox': 'boolean'
4308
+ };
4309
+ return typeMapping[type] || 'string';
4310
+ }
4311
+ renderUploadRecordButton() {
4312
+ if (!this.parsedInputTypes.includes('audio'))
4313
+ return;
4314
+ return (h$1("div", { class: "upload-record-container", onClick: this.triggerAudioRecordUpload }, h$1("input", { type: "file", ref: el => (this.fileInputAudioRecord = el), onChange: this.handleAudioRecordChange, style: { display: 'none' } }), h$1("div", { class: 'upload-record-button' }, h$1("svg", { width: "800px", height: "800px", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, h$1("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M12 2.75C6.89137 2.75 2.75 6.89137 2.75 12C2.75 17.1086 6.89137 21.25 12 21.25C12.6345 21.25 13.2534 21.1862 13.8508 21.065C14.2567 20.9826 14.6526 21.2448 14.735 21.6508C14.8174 22.0567 14.5551 22.4526 14.1492 22.535C13.4541 22.6761 12.7353 22.75 12 22.75C6.06294 22.75 1.25 17.9371 1.25 12C1.25 6.06294 6.06294 1.25 12 1.25C17.9371 1.25 22.75 6.06294 22.75 12C22.75 12.7353 22.6761 13.4541 22.535 14.1492C22.4526 14.5551 22.0567 14.8174 21.6508 14.735C21.2448 14.6526 20.9826 14.2567 21.065 13.8508C21.1862 13.2534 21.25 12.6345 21.25 12C21.25 6.89137 17.1086 2.75 12 2.75ZM12.7676 8.52584C12.7661 8.53409 12.7604 8.56729 12.7564 8.64336C12.7502 8.76101 12.75 8.91982 12.75 9.17082C12.75 9.27795 12.7501 9.33904 12.7518 9.38529C12.7528 9.41425 12.7542 9.42649 12.7546 9.42955C12.7662 9.48945 12.7993 9.54303 12.8477 9.58021C12.8502 9.58194 12.8606 9.58864 12.886 9.60252C12.9266 9.62468 12.9812 9.65209 13.0771 9.7L14.3938 10.3584C14.6183 10.4706 14.7604 10.5414 14.8684 10.5885C14.9382 10.6189 14.9705 10.6287 14.9785 10.631C15.0885 10.6405 15.1917 10.5767 15.2324 10.4742C15.2339 10.4659 15.2396 10.4327 15.2436 10.3566C15.2498 10.239 15.25 10.0802 15.25 9.82918C15.25 9.72205 15.2499 9.66096 15.2482 9.61471C15.2472 9.58575 15.2458 9.57351 15.2454 9.57045C15.2338 9.51055 15.2007 9.45697 15.1523 9.41979C15.1498 9.41805 15.1394 9.41136 15.114 9.39748C15.0734 9.37533 15.0188 9.34791 14.9229 9.3L13.6062 8.64164C13.3817 8.52939 13.2396 8.45859 13.1316 8.41151C13.0617 8.38107 13.0295 8.37131 13.0215 8.36896C12.9115 8.35945 12.8083 8.42327 12.7676 8.52584ZM12.75 11.2135L13.7396 11.7083C13.9425 11.8098 14.1204 11.8987 14.269 11.9635C14.4199 12.0293 14.5988 12.097 14.7972 12.1202C15.6037 12.2142 16.3689 11.7413 16.6454 10.978C16.7134 10.7901 16.7328 10.5998 16.7415 10.4355C16.75 10.2735 16.75 10.0747 16.75 9.8479V9.82918C16.75 9.81565 16.75 9.80205 16.75 9.78837C16.7503 9.62647 16.7505 9.45474 16.7188 9.28904C16.638 8.86674 16.4045 8.48898 16.0629 8.22783C15.9289 8.12535 15.7752 8.04877 15.6303 7.97658C15.618 7.97048 15.6059 7.96441 15.5938 7.95836L14.2603 7.29164C14.0575 7.19022 13.8796 7.10128 13.731 7.03647C13.5801 6.97071 13.4012 6.90297 13.2028 6.87982C12.3963 6.78575 11.6311 7.25868 11.3546 8.02203C11.2866 8.20986 11.2672 8.40019 11.2585 8.56454C11.2519 8.68919 11.2504 8.83571 11.2501 9L11.25 9.11944C11.25 9.13026 11.25 9.14115 11.25 9.1521V9.17082C11.25 9.18435 11.25 9.19795 11.25 9.21163C11.2499 9.23918 11.2499 9.26701 11.25 9.29505V12.5499C10.875 12.3581 10.4501 12.25 10 12.25C8.48122 12.25 7.25 13.4812 7.25 15C7.25 16.5188 8.48122 17.75 10 17.75C11.5188 17.75 12.75 16.5188 12.75 15V11.2135ZM11.25 15C11.25 14.3096 10.6904 13.75 10 13.75C9.30964 13.75 8.75 14.3096 8.75 15C8.75 15.6904 9.30964 16.25 10 16.25C10.6904 16.25 11.25 15.6904 11.25 15ZM17.4697 14.4697C17.7626 14.1768 18.2374 14.1768 18.5303 14.4697L21.0303 16.9697C21.3232 17.2626 21.3232 17.7374 21.0303 18.0303C20.7374 18.3232 20.2626 18.3232 19.9697 18.0303L18.75 16.8107V22C18.75 22.4142 18.4142 22.75 18 22.75C17.5858 22.75 17.25 22.4142 17.25 22V16.8107L16.0303 18.0303C15.7374 18.3232 15.2626 18.3232 14.9697 18.0303C14.6768 17.7374 14.6768 17.2626 14.9697 16.9697L17.4697 14.4697Z" })))));
4315
+ }
4316
+ renderRecordButton() {
4317
+ if (!this.parsedInputTypes.includes('voice'))
4318
+ return;
4319
+ const buttonClass = [
4320
+ 'record-button',
4321
+ this.isRecording && 'recording',
4322
+ this.isProcessing && 'processing'
4323
+ ].filter(Boolean).join(' ');
4324
+ const isDisabled = this.isProcessing || this.hasError;
4325
+ return (h$1("button", { class: buttonClass, onClick: () => this.handleRecordClick(), disabled: isDisabled, "aria-label": this.isRecording ? 'Stop recording' : 'Start recording' }, this.isProcessing ? (h$1("svg", { class: "record-icon", viewBox: "0 0 24 24" }, h$1("circle", { cx: "12", cy: "12", r: "3" }, h$1("animate", { attributeName: "r", values: "3;6;3", dur: "1s", repeatCount: "indefinite" }), h$1("animate", { attributeName: "opacity", values: "1;0.3;1", dur: "1s", repeatCount: "indefinite" })))) : this.isRecording ? (h$1("svg", { class: "record-icon", viewBox: "0 0 24 24" }, h$1("rect", { x: "6", y: "6", width: "12", height: "12", rx: "2" }))) : (h$1("svg", { class: "record-icon", viewBox: "0 0 24 24" }, h$1("circle", { cx: "12", cy: "12", r: "8" })))));
4326
+ }
4327
+ renderStatusMessage() {
4328
+ const statusClass = [
4329
+ 'status-text',
4330
+ this.hasError && 'error',
4331
+ this.filledData && !this.hasError && 'success'
4332
+ ].filter(Boolean).join(' ');
4333
+ return h$1("div", { class: statusClass }, this.statusMessage);
4334
+ }
4335
+ renderFormPreview() {
4336
+ if (!this.parsedSchema)
4337
+ return null;
4338
+ const isPreview = this.isReadonlyMode && !this.filledData;
4339
+ const title = isPreview ? 'Form Preview (Voice input to fill)' : 'Voice-Filled Form:';
4340
+ return (h$1("div", { class: "form-preview" }, h$1("div", { class: "form-preview-title" }, title), h$1("form", { class: "voice-filled-form" }, this.renderFormFields())));
4341
+ }
4342
+ renderFormFields() {
4343
+ // console.log("renderFormFields", this.parsedSchema);
4344
+ if (!this.parsedSchema)
4345
+ return null;
4346
+ switch (this.context) {
4347
+ case "ecoteka":
4348
+ // console.log("TODO renderFormFields", this.parsedSchema);
4349
+ case "ng":
4350
+ return this.parsedSchema.Children.map((child) => {
4351
+ var _a, _b, _c;
4352
+ if (!child.System_Name || !child.Type)
4353
+ return null;
4354
+ const fieldName = child.System_Name;
4355
+ const fieldType = this.mapFieldType(child.Type);
4356
+ const fieldLabel = ((_a = child.Settings) === null || _a === void 0 ? void 0 : _a.Label) || child.System_Name;
4357
+ const isRequired = child.Required || false;
4358
+ const fieldValue = (_b = child.Settings) === null || _b === void 0 ? void 0 : _b.Default_Value;
4359
+ return (h$1("div", { class: "form-group", key: fieldName }, h$1("label", { htmlFor: fieldName, class: "form-label" }, fieldLabel, isRequired && h$1("span", { class: "required" }, "*")), this.renderFormField(fieldName, {
4360
+ type: fieldType,
4361
+ title: fieldLabel,
4362
+ required: isRequired,
4363
+ options: (_c = child.Children) === null || _c === void 0 ? void 0 : _c.map((option) => option.System_Name || option.Label || option.toString())
4364
+ }, fieldValue)));
4365
+ }).filter(Boolean);
4366
+ case "ecoll-veto":
4367
+ // NOTE STEP 2
4368
+ // console.log("TODO renderFormFields", this.parsedSchema);
4369
+ const mergedItemsSchema = (this.parsedSchema[0].items).concat(this.parsedSchema[1].items);
4370
+ return Object.entries(mergedItemsSchema).map(([key, field]) => {
4371
+ var _a, _b;
4372
+ const fieldName = field.name;
4373
+ field.type = this.mapFieldType(field.type);
4374
+ const fieldLabel = field.label || fieldName;
4375
+ const isRequired = field.required || false;
4376
+ const fieldValue = this.parsedSchema[2][fieldName];
4377
+ // if (['position', 'thesaurus'].includes(field.type)) {
4378
+ // try {
4379
+ // const response = await fetch(`${this.classificationRootUrl}/ng/api/v1/classification/getList/${fieldType.toLowerCase() == 'position' ? "Position" : "Thesaurus"}/?StartNodeID=${field.config.options.options.startNode}`);
4380
+ // if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
4381
+ // const data = await response.json();
4382
+ // if (Array.isArray(data)) {
4383
+ // const options = data.map(item => ({
4384
+ // value: item.ID,
4385
+ // label: item.System_Name
4386
+ // }));
4387
+ // if (options.length > 0) {
4388
+ // field.pickerOptions = options;
4389
+ // // TODO on degage les quotes simples temporairement, a corriger
4390
+ // field.options = options.map(option => option.label.replace("'", ""));
4391
+ // }
4392
+ // } else {
4393
+ // console.error("Unexpected API response format:", data);
4394
+ // }
4395
+ // } catch (error) {
4396
+ // console.error("Error fetching classification data:", error);
4397
+ // }
4398
+ // }
4399
+ console.log("filling with", field);
4400
+ return (h$1("div", { class: "form-group", key: fieldName }, h$1("label", { htmlFor: fieldName, class: "form-label" }, fieldLabel, isRequired && h$1("span", { class: "required" }, "*")), this.renderFormField(fieldName, field, ((_b = (_a = this.filledData) === null || _a === void 0 ? void 0 : _a[fieldName]) !== null && _b !== void 0 ? _b : fieldValue))));
4401
+ });
4402
+ case "track":
4403
+ default:
4404
+ return Object.entries(this.parsedSchema.fields).map(([fieldName, field]) => {
4405
+ var _a, _b;
4406
+ return (h$1("div", { class: "form-group", key: fieldName }, h$1("label", { htmlFor: fieldName, class: "form-label" }, field.title || fieldName, field.required && h$1("span", { class: "required" }, "*")), this.renderFormField(fieldName, field, ((_b = (_a = this.filledData) === null || _a === void 0 ? void 0 : _a[fieldName]) !== null && _b !== void 0 ? _b : field.value))));
4407
+ });
4408
+ }
4409
+ }
4410
+ renderFormField(fieldName, field, value) {
4411
+ var _a, _b, _c, _d;
4412
+ const isReadonly = this.isReadonlyMode && !this.filledData;
4413
+ const commonProps = {
4414
+ id: fieldName,
4415
+ name: fieldName,
4416
+ class: 'form-input',
4417
+ required: field.required,
4418
+ disabled: isReadonly
4419
+ };
4420
+ switch (field.type) {
4421
+ case 'multiselect':
4422
+ if (isReadonly) {
4423
+ return (h$1("div", { class: "readonly-select" }, h$1("div", { class: "select-placeholder" }, "Available options:"), h$1("ul", { class: "select-options-list" }, (_a = field.options) === null || _a === void 0 ? void 0 : _a.map(option => (h$1("li", { class: "select-option" }, option))))));
4424
+ }
4425
+ const selectedValues = Array.isArray(value) ? value : (value ? [value] : []);
4426
+ return (h$1("div", { class: "multiselect-container" }, (_b = field.options) === null || _b === void 0 ? void 0 : _b.map(option => {
4427
+ const isChecked = selectedValues.some(v => (v === null || v === void 0 ? void 0 : v.toString().toLowerCase()) === (option === null || option === void 0 ? void 0 : option.toString().toLowerCase()));
4428
+ return (h$1("label", { class: "multiselect-option" }, h$1("input", { type: "checkbox", name: fieldName, value: option, checked: isChecked, disabled: isReadonly }), h$1("span", { class: "multiselect-label" }, option)));
4429
+ })));
4430
+ case 'select':
4431
+ if (isReadonly) {
4432
+ // In readonly mode, show all options as a list instead of dropdown
4433
+ return (h$1("div", { class: "readonly-select" }, h$1("div", { class: "select-placeholder" }, "Available options:"), h$1("ul", { class: "select-options-list" }, (_c = field.options) === null || _c === void 0 ? void 0 : _c.map(option => (h$1("li", { class: "select-option" }, option))))));
4434
+ }
4435
+ return (h$1("select", { id: fieldName, name: fieldName, class: "form-input", required: field.required }, h$1("option", { value: "" }, "-- Select --"), (_d = field.options) === null || _d === void 0 ? void 0 :
4436
+ _d.map(option => (h$1("option", { value: option, selected: value === option }, option)))));
4437
+ case 'boolean':
4438
+ return (h$1("input", Object.assign({}, commonProps, { type: "checkbox", class: "form-checkbox", checked: value === true || value === 'true' })));
4439
+ case 'number':
4440
+ return (h$1("input", Object.assign({}, commonProps, { type: "number", min: field.min, max: field.max, step: "any", value: value || '' })));
4441
+ case 'date':
4442
+ return (h$1("input", Object.assign({}, commonProps, { type: 'date', value: value ? (([d, m, y]) => `${y}-${m}-${d}`)(value.split("/")) : '' })));
4443
+ case 'datetime':
4444
+ return (h$1("input", Object.assign({}, commonProps, { type: 'datetime-local', value: value || '' })));
4445
+ default: // string
4446
+ return (h$1("input", Object.assign({}, commonProps, { type: "text", pattern: field.pattern, placeholder: field.description, value: value || '' })));
4447
+ }
4448
+ }
4449
+ renderDebugPanel() {
4450
+ if (!this.debug)
4451
+ return null;
4452
+ return (h$1("div", { class: "debug-panel" }, h$1("div", { class: "debug-title" }, "Debug Information:"), h$1("div", { class: "debug-content" }, JSON.stringify(this.debugInfo, null, 2))));
4453
+ }
4454
+ render() {
4455
+ return (h$1("div", { key: '2021f0d9a0fdb1ac5b87ba301b7973a11f398f1e' }, h$1("div", { key: '2d0e9bc170c91d70f9bfbdb3b43e9ff3b884ff33', class: "voice-recorder-container" + (this.debug || this.renderForm ? "-debug" : "") }, h$1("div", { key: '6914d9a901beaf8c0671b96e4bfd7fb54d5e83ca', class: "row-audio-area" }, this.renderRecordButton(), this.renderUploadRecordButton()), this.displayStatus ? this.renderStatusMessage() : "", this.renderUploadButton(), this.renderForm ? this.renderFormPreview() : "", this.debug ? this.renderDebugPanel() : "")));
4456
+ }
4457
+ static get watchers() { return {
4458
+ "formJson": ["initializeServices"],
4459
+ "serviceConfig": ["initializeServices"]
4460
+ }; }
4461
+ };
4462
+ VoiceFormRecorder.style = voiceInputModuleCss;
4463
+
4464
+ export { VoiceFormRecorder as voice_input_module };
4465
+ //# sourceMappingURL=voice-input-module.entry.esm.js.map
4466
+
4467
+ //# sourceMappingURL=voice-input-module.entry.js.map