reneco-advanced-input-module 0.0.1 → 0.0.3

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