forked from IntelliTect/EssentialCSharp.Web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrydotnet-module.js
More file actions
675 lines (592 loc) · 23.9 KB
/
trydotnet-module.js
File metadata and controls
675 lines (592 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
// TryDotNet Module - Vue.js composable for interactive code execution
import { ref, nextTick, onMounted, onUnmounted } from 'vue';
// Timeout durations (ms)
const HEALTH_CHECK_TIMEOUT = 5000;
const SESSION_CREATION_TIMEOUT = 20000;
const RUN_TIMEOUT = 30000;
// User-friendly error messages
const ERROR_MESSAGES = {
serviceUnavailable: 'The code execution service is currently unavailable. Please try again later.',
serviceNotConfigured: 'Interactive code execution is not available at this time.',
sessionTimeout: 'The code editor took too long to load. The service may be temporarily unavailable.',
runTimeout: 'Code execution timed out. The service may be temporarily unavailable.',
editorNotFound: 'Could not initialize the code editor. Please try again.',
sessionNotInitialized: 'The code editor session is not ready. Please try reopening the code runner.',
fetchFailed: 'Could not load the listing source code. Please try again.',
};
/**
* Races a promise against a timeout. Rejects with the given message if the
* timeout fires first.
* @param {Promise} promise - The promise to race
* @param {number} ms - Timeout in milliseconds
* @param {string} timeoutMsg - Message for the timeout error
* @returns {Promise}
*/
function withTimeout(promise, ms, timeoutMsg) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(timeoutMsg)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
/**
* Checks whether the TryDotNet origin is configured and non-empty.
* @returns {boolean}
*/
function isTryDotNetConfigured() {
const origin = window.TRYDOTNET_ORIGIN;
return typeof origin === 'string' && origin.trim().length > 0;
}
// ── Runnable-listings data (loaded once from chapter-listings.json) ──────────
/** @type {Promise<Set<string>>|null} */
let _runnableListingsPromise = null;
/**
* Loads chapter-listings.json (once) and builds a Set of normalised
* "chapter.listing" keys, e.g. "1.3", "12.50".
* Only includes listings where both can_compile and can_run are true.
* @returns {Promise<Set<string>>}
*/
function loadRunnableListings() {
if (_runnableListingsPromise) return _runnableListingsPromise;
_runnableListingsPromise = fetch('/js/chapter-listings.json')
.then(res => {
if (!res.ok) {
const msg = res.status === 404
? 'chapter-listings.json not found (404). The NuGet content package may not be restored — Run buttons will not be shown.'
: `Failed to load chapter-listings.json: ${res.status}`;
throw new Error(msg);
}
return res.json();
})
.then(data => {
const set = new Set();
const chapters = data.chapters || {};
for (const [, files] of Object.entries(chapters)) {
for (const fileObj of files) {
// fileObj is now { filename: "01.03.cs", can_compile: true, can_run: true }
if (!fileObj.can_compile || !fileObj.can_run) continue; // Skip listings that can't compile or can't run
const filename = fileObj.filename;
// filename looks like "01.03.cs" → chapter 1, listing 3
const m = filename.match(/^(\d+)\.(\d+)\./);
if (m) {
set.add(`${parseInt(m[1], 10)}.${parseInt(m[2], 10)}`);
}
}
}
return set;
})
.catch(err => {
console.warn('Could not load runnable listings:', err);
_runnableListingsPromise = null; // Allow retry on next call (e.g. transient network error)
return new Set(); // graceful degradation — no Run buttons
});
return _runnableListingsPromise;
}
/**
* Strips #region / #endregion directive lines (INCLUDE, EXCLUDE, etc.)
* from source code while keeping the code between them intact.
* @param {string} code - Raw source code
* @returns {string} Code with region directive lines removed
*/
function stripRegionDirectives(code) {
return code.replace(/^\s*#(?:region|endregion)\s+(?:INCLUDE|EXCLUDE).*$/gm, '').trim();
}
/**
* Creates scaffolding for user code to run in the TryDotNet environment.
* @param {string} userCode - The user's C# code to wrap
* @returns {string} Scaffolded code with proper using statements and Main method
*/
function createScaffolding(userCode) {
return `
namespace Program
{
class Program
{
static void Main(string[] args)
{
#region controller
${userCode}
#endregion
}
}
}`;
}
/**
* Dynamically loads a script and returns a promise that resolves when loaded.
* @param {string} url - URL of the script to load
* @param {string} globalName - Name of the global variable the script creates
* @param {number} timeLimit - Maximum time to wait for script load
* @returns {Promise<any>} Promise resolving to the global object
*/
function loadLibrary(url, globalName, timeLimit = 15000) {
return new Promise((resolve, reject) => {
// Check if already loaded
if (globalName && window[globalName]) {
resolve(window[globalName]);
return;
}
const timeout = setTimeout(() => {
reject(new Error(`${url} load timeout`));
}, timeLimit);
const script = document.createElement('script');
script.src = url;
script.async = true;
script.defer = true;
script.crossOrigin = 'anonymous';
script.onload = () => {
clearTimeout(timeout);
if (globalName && !window[globalName]) {
reject(new Error(`${url} loaded but ${globalName} is undefined`));
} else {
resolve(window[globalName]);
}
};
script.onerror = () => {
clearTimeout(timeout);
reject(new Error(`Failed to load ${url}`));
};
document.head.appendChild(script);
});
}
/**
* Vue composable for TryDotNet code execution functionality.
* @returns {Object} Composable state and methods
*/
export function useTryDotNet() {
// State
const isCodeRunnerOpen = ref(false);
const codeRunnerLoading = ref(false);
const codeRunnerError = ref(null);
const codeRunnerOutput = ref('');
const codeRunnerOutputError = ref(false);
const currentListingInfo = ref(null);
const isRunning = ref(false);
const isLibraryLoaded = ref(false);
// Internal state (not exposed)
let trydotnet = null;
let session = null;
let editorElement = null;
let currentLoadedListing = null; // Track which listing is currently loaded
/**
* Gets the TryDotNet origin URL from config.
* @returns {string} The TryDotNet service origin URL
*/
function getTryDotNetOrigin() {
return window.TRYDOTNET_ORIGIN;
}
/**
* Performs a lightweight reachability check against the TryDotNet origin.
* Rejects with a user-friendly message when the service is unreachable.
* @returns {Promise<void>}
*/
async function checkServiceHealth() {
const origin = getTryDotNetOrigin();
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT);
try {
// Check the actual script endpoint rather than the bare origin,
// which may not have a handler and would return 404.
const res = await fetch(`${origin}/api/trydotnet.min.js`, {
method: 'HEAD',
mode: 'no-cors',
signal: controller.signal,
});
// mode: 'no-cors' gives an opaque response (status 0), which is fine
// — we only care that the network request didn't fail.
} catch {
throw new Error(ERROR_MESSAGES.serviceUnavailable);
} finally {
clearTimeout(timer);
}
}
/**
* Loads the TryDotNet library from the service.
* Performs a health check first to fail fast.
* @returns {Promise<void>}
*/
async function loadTryDotNetLibrary() {
if (isLibraryLoaded.value && trydotnet) {
return;
}
if (!isTryDotNetConfigured()) {
throw new Error(ERROR_MESSAGES.serviceNotConfigured);
}
// Fail fast if the service is unreachable
await checkServiceHealth();
const origin = getTryDotNetOrigin();
const trydotnetUrl = `${origin}/api/trydotnet.min.js`;
try {
trydotnet = await loadLibrary(trydotnetUrl, 'trydotnet', 15000);
if (!trydotnet) {
throw new Error(ERROR_MESSAGES.serviceUnavailable);
}
isLibraryLoaded.value = true;
} catch (error) {
console.error('Failed to load TryDotNet library:', error);
throw new Error(ERROR_MESSAGES.serviceUnavailable);
}
}
/**
* Creates a TryDotNet session with the editor iframe and initial code.
* @param {HTMLElement} editorEl - The iframe element for the Monaco editor
* @param {string} userCode - The C# code to display in the editor
* @returns {Promise<void>}
*/
async function createSession(editorEl, userCode) {
if (!trydotnet) {
throw new Error('TryDotNet library not loaded');
}
editorElement = editorEl;
const hostOrigin = window.location.origin;
window.postMessage({ type: 'HostEditorReady', editorId: '0' }, hostOrigin);
const fileName = 'Program.cs';
const isComplete = isCompleteProgram(userCode);
const fileContent = isComplete ? userCode : createScaffolding(userCode);
const files = [{ name: fileName, content: fileContent }];
const project = { package: 'console', files: files };
const document = isComplete
? fileName
: { fileName: fileName, region: 'controller' };
const configuration = {
hostOrigin: hostOrigin,
trydotnetOrigin: getTryDotNetOrigin(),
enableLogging: false
};
session = await withTimeout(
trydotnet.createSessionWithProjectAndOpenDocument(
configuration,
[editorElement],
window,
project,
document
),
SESSION_CREATION_TIMEOUT,
ERROR_MESSAGES.sessionTimeout
);
// Subscribe to output events
session.subscribeToOutputEvents((event) => {
handleOutput(event);
});
}
/**
* Sets code in the Monaco editor.
* @param {string} userCode - The C# code to display in the editor
* @returns {Promise<void>}
*/
async function setCode(userCode) {
if (!session || !trydotnet) {
throw new Error('Session not initialized');
}
const isComplete = isCompleteProgram(userCode);
const fileContent = isComplete ? userCode : createScaffolding(userCode);
const fileName = 'Program.cs';
const files = [{ name: fileName, content: fileContent }];
const project = await trydotnet.createProject({
packageName: 'console',
files: files
});
await session.openProject(project);
const defaultEditor = session.getTextEditor();
const documentOptions = {
fileName: fileName,
editorId: defaultEditor.id()
};
// Only add region for scaffolded code
if (!isComplete) {
documentOptions.region = 'controller';
}
await session.openDocument(documentOptions);
}
/**
* Runs the code currently in the editor.
* @returns {Promise<void>}
*/
async function runCode() {
if (!session) {
codeRunnerOutput.value = ERROR_MESSAGES.sessionNotInitialized;
codeRunnerOutputError.value = true;
return;
}
codeRunnerOutput.value = 'Running...';
codeRunnerOutputError.value = false;
isRunning.value = true;
try {
await withTimeout(session.run(), RUN_TIMEOUT, ERROR_MESSAGES.runTimeout);
} catch (error) {
codeRunnerOutput.value = error.message;
codeRunnerOutputError.value = true;
} finally {
isRunning.value = false;
}
}
/**
* Clears the editor content.
*/
function clearEditor() {
if (!session) return;
const textEditor = session.getTextEditor();
if (textEditor) {
textEditor.setContent('');
codeRunnerOutput.value = 'Editor cleared.';
codeRunnerOutputError.value = false;
}
}
/**
* Handles output events from the TryDotNet session.
* @param {Object} event - Output event from TryDotNet
*/
function handleOutput(event) {
if (event.exception) {
codeRunnerOutput.value = event.exception.join('\n');
codeRunnerOutputError.value = true;
} else if (event.diagnostics && event.diagnostics.length > 0) {
// Handle compilation errors/warnings
const diagnosticMessages = event.diagnostics.map(d => {
const severity = d.severity || 'Error';
const location = d.location ? `(${d.location})` : '';
const id = d.id ? `${d.id}: ` : '';
return `${severity} ${location}: ${id}${d.message}`;
});
codeRunnerOutput.value = diagnosticMessages.join('\n');
codeRunnerOutputError.value = true;
} else if (event.stderr && event.stderr.length > 0) {
// Handle standard error output
codeRunnerOutput.value = event.stderr.join('\n');
codeRunnerOutputError.value = true;
} else if (event.stdout) {
codeRunnerOutput.value = event.stdout.join('\n');
codeRunnerOutputError.value = false;
} else {
codeRunnerOutput.value = 'No output';
codeRunnerOutputError.value = false;
}
isRunning.value = false;
}
/**
* Checks if code is a complete C# program that doesn't need scaffolding.
* A program is "complete" when it contains a namespace declaration, OR
* when it defines any class with a static Main method.
* Top-level statement files (no class, no namespace) return false and
* will be wrapped by createScaffolding().
* @param {string} code - Source code to check
* @returns {boolean} True if code is complete, false if it needs scaffolding
*/
function isCompleteProgram(code) {
// Check for explicit namespace declaration (most reliable indicator)
const hasNamespace = /namespace\s+\w+/i.test(code);
// Check if any class has a static Main method
const hasClassWithMain = /class\s+\w+/.test(code) &&
/static\s+(void|async\s+Task)\s+Main\s*\(/.test(code);
return hasNamespace || hasClassWithMain;
}
/**
* Fetches listing source code from the API.
* @param {string|number} chapter - Chapter number
* @param {string|number} listing - Listing number
* @returns {Promise<string>} The listing source code (extracted snippet)
*/
async function fetchListingCode(chapter, listing) {
const response = await fetch(`/api/ListingSourceCode/chapter/${chapter}/listing/${listing}`);
if (!response.ok) {
throw new Error(ERROR_MESSAGES.fetchFailed);
}
const data = await response.json();
const code = data.content || '';
// Complete programs (namespace or class+Main) are sent as-is, but
// with common usings prepended when the file has none — TryDotNet's
// 'console' package does not provide SDK implicit global usings.
// Top-level statement files get region directives stripped so the
// scaffolding wrapper doesn't contain raw #region lines.
if (isCompleteProgram(code)) {
return code;
}
return stripRegionDirectives(code);
}
/**
* Opens the code runner panel with a specific listing.
* @param {string|number} chapter - Chapter number
* @param {string|number} listing - Listing number
* @param {string} title - Title to display
*/
async function openCodeRunner(chapter, listing, title) {
currentListingInfo.value = { chapter, listing, title };
isCodeRunnerOpen.value = true;
codeRunnerLoading.value = true;
codeRunnerError.value = null;
codeRunnerOutput.value = 'Click "Run" to execute the code.';
codeRunnerOutputError.value = false;
const listingKey = `${chapter}.${listing}`;
try {
// Load the library if not already loaded
if (!isLibraryLoaded.value) {
await loadTryDotNetLibrary();
}
// Wait for the panel to render and get the editor element
await nextTick();
const editorEl = document.querySelector('.code-runner-editor');
if (!editorEl) {
throw new Error(ERROR_MESSAGES.editorNotFound);
}
// Check if this listing is already loaded in the session
if (session && currentLoadedListing === listingKey) {
// Listing already loaded, just show the panel
codeRunnerLoading.value = false;
return;
}
// Fetch the listing code
const code = await fetchListingCode(chapter, listing);
// Create session if needed with the fetched code
if (!session) {
await createSession(editorEl, code);
currentLoadedListing = listingKey;
} else {
// Session exists, update the code
await setCode(code);
currentLoadedListing = listingKey;
}
codeRunnerLoading.value = false;
} catch (error) {
console.error('Failed to open code runner:', error);
codeRunnerError.value = error.message || ERROR_MESSAGES.serviceUnavailable;
codeRunnerLoading.value = false;
}
}
/**
* Retries opening the code runner after a failure.
* Resets the session so a fresh connection is attempted.
*/
function retryCodeRunner() {
// Reset session state so a fresh connection is attempted
session = null;
currentLoadedListing = null;
isLibraryLoaded.value = false;
trydotnet = null;
if (currentListingInfo.value) {
const { chapter, listing, title } = currentListingInfo.value;
openCodeRunner(chapter, listing, title);
}
}
/**
* Closes the code runner panel.
*/
function closeCodeRunner() {
isCodeRunnerOpen.value = false;
currentListingInfo.value = null;
// Note: We keep the session and currentLoadedListing to avoid recreating when reopened
}
/**
* Clears the output console.
*/
function clearOutput() {
codeRunnerOutput.value = '';
codeRunnerOutputError.value = false;
}
/**
* Injects Run buttons into code block sections.
* Skipped entirely when TryDotNet origin is not configured.
* Only adds buttons for listings present in chapter-listings.json.
*/
async function injectRunButtons() {
if (!isTryDotNetConfigured()) {
return; // Don't show Run buttons when the service is not configured
}
// Pre-load the runnable listings set so we can check membership below
const runnableSet = await loadRunnableListings();
if (runnableSet.size === 0) {
return; // JSON failed to load or is empty — no buttons
}
const codeBlocks = document.querySelectorAll('.code-block-section');
codeBlocks.forEach((block) => {
const heading = block.querySelector('.code-block-heading');
if (!heading) return;
// Skip if button already injected
if (heading.querySelector('.code-runner-btn')) return;
// Parse chapter and listing numbers from the heading
// Format 1: <span class="CDTNUM">Listing </span><span class="TBLNUM">1.</span><span class="CDTNUM">22</span>
// Format 2: <span class="CDTNUM">Listing</span> <span class="TBLNUM">1.</span>1: Title
let chapter = null;
let listing = null;
// First, try to extract from the full heading text
// Pattern: "Listing 1.22" or "Listing 1.1:"
const headingText = heading.textContent;
const listingMatch = headingText.match(/Listing\s+(\d+)\.(\d+)/i);
if (listingMatch) {
chapter = listingMatch[1];
listing = listingMatch[2];
} else {
// Fallback to old method for other formats
const spans = heading.querySelectorAll('span');
spans.forEach((span) => {
if (span.classList.contains('TBLNUM')) {
// Extract chapter number (format: "1." -> "1")
const match = span.textContent.match(/(\d+)\./);
if (match) {
chapter = match[1];
}
}
if (span.classList.contains('CDTNUM') && chapter !== null && listing === null) {
// The CDTNUM after TBLNUM contains the listing number
const num = span.textContent.trim();
if (/^\d+$/.test(num)) {
listing = num;
}
}
});
}
// Only add button for listings present in the curated JSON
if (chapter && listing && runnableSet.has(`${parseInt(chapter, 10)}.${parseInt(listing, 10)}`)) {
// Wrap existing content in a span to keep it together
const contentWrapper = document.createElement('span');
while (heading.firstChild) {
contentWrapper.appendChild(heading.firstChild);
}
// Make heading a flex container
heading.style.display = 'flex';
heading.style.justifyContent = 'space-between';
heading.style.alignItems = 'center';
// Add wrapped content back
heading.appendChild(contentWrapper);
// Create run button
const runButton = document.createElement('button');
runButton.className = 'code-runner-btn';
runButton.type = 'button';
runButton.title = `Run Listing ${chapter}.${listing}`;
runButton.innerHTML = '<i class="mdi mdi-play-circle-outline" aria-hidden="true"></i> Run';
runButton.setAttribute('aria-label', `Run Listing ${chapter}.${listing}`);
runButton.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
openCodeRunner(chapter, listing, `Listing ${chapter}.${listing}`);
});
heading.appendChild(runButton);
}
});
}
// Lifecycle hooks
onMounted(() => {
// Inject run buttons after component mounts
nextTick(() => {
injectRunButtons();
});
});
// Return composable interface
return {
// State
isCodeRunnerOpen,
codeRunnerLoading,
codeRunnerError,
codeRunnerOutput,
codeRunnerOutputError,
currentListingInfo,
isRunning,
isLibraryLoaded,
// Methods
openCodeRunner,
closeCodeRunner,
retryCodeRunner,
runCode,
clearEditor,
clearOutput,
injectRunButtons
};
}