-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_blockly_assets.mjs
More file actions
2280 lines (2208 loc) · 74.7 KB
/
Copy pathtest_blockly_assets.mjs
File metadata and controls
2280 lines (2208 loc) · 74.7 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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
// Part of PyBLE (https://pyble.dev) — see /LICENSE.
/**
* Headless smoke test for the committed offline Blockly runtime.
*
* Run after tools/build_blockly_assets.sh. It uses the pinned upstream's
* build-only puppeteer-core and a locally installed Chrome/Chromium; neither is
* a shipped app dependency.
*/
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { fileURLToPath, pathToFileURL } from "node:url";
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.dirname(scriptDir);
const puppeteerUrl = pathToFileURL(
path.join(
repoRoot,
"app/upstream/blockly/node_modules/puppeteer-core/lib/puppeteer/puppeteer-core.js",
),
);
const { default: puppeteer } = await import(puppeteerUrl.href);
const browserCandidates = [
process.env.CHROME_BIN,
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/usr/bin/google-chrome",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
].filter(Boolean);
const executablePath = browserCandidates.find((candidate) =>
fs.existsSync(candidate),
);
if (!executablePath) {
throw new Error("Chrome/Chromium not found; set CHROME_BIN.");
}
const browser = await puppeteer.launch({
executablePath,
headless: true,
args: ["--allow-file-access-from-files"],
});
try {
const page = await browser.newPage();
await page.setViewport({ width: 1024, height: 760, deviceScaleFactor: 1 });
const requests = [];
const pageErrors = [];
page.on("request", (request) => requests.push(request.url()));
page.on("pageerror", (error) => pageErrors.push(String(error)));
await page.evaluateOnNewDocument(() => {
window.__pybleMessages = [];
window.PybleBlocks = {
postMessage(message) {
window.__pybleMessages.push(JSON.parse(message));
},
};
});
const localizedHostMessages = {
examplesCategory: "Localized starter examples",
exampleTitles: {
"hello-pyble": "Localized greeting",
"count-repeatedly": "Localized counting",
"blink-led": "Localized blinking",
"blink-neopixel": "Localized RGB blinking",
"read-button": "Localized input",
"button-controls-led": "Localized control",
"reusable-function": "Localized function",
},
timeCategory: "Localized timing",
timeBlockMessage: "localized wait %1 milliseconds",
timeBlockTooltip: "Localized timing tooltip.",
timeRequiredError: "Localized duration is required.",
timeInvalidError: "Localized duration must be a safe integer.",
gpioCategory: "E/S numériques localisées",
gpioPinMessage: "BROCHE-LOCALE %1 MODE-LOCAL %2 TIRAGE-LOCAL %3",
gpioModeInput: "entrée locale",
gpioModeOutput: "sortie locale",
gpioPullNone: "sans tirage local",
gpioPullUp: "tirage haut local",
gpioPullDown: "tirage bas local",
gpioPinTooltip: "Info-broche localisée.",
gpioWriteMessage: "ÉCRIRE-LOCAL %1 NIVEAU-LOCAL %2",
gpioLevelLow: "niveau bas local",
gpioLevelHigh: "niveau haut local",
gpioWriteTooltip: "Info-écriture localisée.",
gpioReadMessage: "LIRE-LOCAL %1",
gpioReadTooltip: "Info-lecture localisée.",
gpioPinRequiredError: "Broche locale requise.",
gpioPinInvalidError: "Numéro de broche local invalide.",
gpioModeInvalidError: "Mode de broche local invalide.",
gpioPullInvalidError: "Tirage de broche local invalide.",
gpioWritePinRequiredError: "Broche d’écriture locale requise.",
gpioLevelInvalidError: "Niveau de sortie local invalide.",
gpioReadPinRequiredError: "Broche de lecture locale requise.",
gpioRestoreModeInvalidError: "Mode restauré local invalide.",
gpioRestorePullInvalidError: "Tirage restauré local invalide.",
gpioRestoreLevelInvalidError: "Niveau restauré local invalide.",
neopixelCategory: "Pixels RVB localisés",
neopixelCreateMessage: "CRÉER-PIXEL-LOCAL broche %1 nombre %2",
neopixelRgbMessage: "COULEUR-LOCALE rouge %1 vert %2 bleu %3",
neopixelSetPixelMessage: "RÉGLER-PIXEL-LOCAL ruban %1 index %2 couleur %3",
neopixelFillMessage: "REMPLIR-PIXELS-LOCAL ruban %1 couleur %2",
neopixelWriteMessage: "AFFICHER-PIXELS-LOCAL ruban %1",
neopixelCreateTooltip: "Info-création NeoPixel localisée.",
neopixelRgbTooltip: "Info-couleur NeoPixel localisée.",
neopixelSetPixelTooltip: "Info-pixel individuel localisée.",
neopixelFillTooltip: "Info-remplissage NeoPixel localisée.",
neopixelWriteTooltip: "Info-transmission NeoPixel localisée.",
neopixelPinRequiredError: "Broche NeoPixel locale requise.",
neopixelPixelsRequiredError: "Nombre de pixels local requis.",
neopixelPixelsInvalidError:
"Nombre de pixels local doit être un entier positif sûr.",
neopixelRedRequiredError: "Composante rouge locale requise.",
neopixelGreenRequiredError: "Composante verte locale requise.",
neopixelBlueRequiredError: "Composante bleue locale requise.",
neopixelStripRequiredError: "Ruban NeoPixel local requis.",
neopixelIndexRequiredError: "Index NeoPixel local requis.",
neopixelColorRequiredError: "Couleur NeoPixel locale requise.",
multilineValueError: "Valeur locale multiligne refusée.",
};
const indexUrl = pathToFileURL(
path.join(repoRoot, "app/assets/blockly/index.html"),
);
await page.goto(indexUrl.href, { waitUntil: "load" });
const hostEpoch = 101;
const invalidHostEpoch = await page.evaluate((messages) => {
try {
window.pybleBlocks.configureHost(messages, 0);
return "accepted";
} catch (error) {
return String(error);
}
}, localizedHostMessages);
if (!invalidHostEpoch.includes("host epoch")) {
throw new Error(
`Blockly accepted an invalid Dart host epoch: ${invalidHostEpoch}`,
);
}
const hostConfiguration = await page.evaluate(({ messages, epoch }) => {
const configurable =
typeof window.pybleBlocks?.configureHost === "function";
return {
configurable,
accepted: configurable
? window.pybleBlocks.configureHost(messages, epoch)
: false,
};
}, { messages: localizedHostMessages, epoch: hostEpoch });
if (!hostConfiguration.configurable || hostConfiguration.accepted !== true) {
throw new Error(
`localized Blockly host configuration failed: ${JSON.stringify(hostConfiguration)}`,
);
}
await page.waitForFunction(() =>
window.__pybleMessages.some((message) => message.type === "snapshot"),
);
const initialSnapshot = await page.evaluate(() =>
window.__pybleMessages.find((message) => message.type === "snapshot"),
);
if (
!initialSnapshot ||
JSON.stringify(initialSnapshot.workspace) !== "{}"
) {
throw new Error(
`Blockly's canonical empty serialization changed: ${JSON.stringify(initialSnapshot)}`,
);
}
async function assertWorkspaceGeometry(width, height) {
await page.setViewport({ width, height, deviceScaleFactor: 1 });
await page.waitForFunction(
(expectedWidth, expectedHeight) => {
const svg = document.querySelector(".blocklySvg");
if (!svg) return false;
const rect = svg.getBoundingClientRect();
return (
Math.abs(rect.width - expectedWidth) <= 1 &&
Math.abs(rect.height - expectedHeight) <= 1
);
},
{},
width,
height,
);
const geometry = await page.evaluate(() => {
const svg = document.querySelector(".blocklySvg").getBoundingClientRect();
return {
svg: { width: svg.width, height: svg.height },
viewport: { width: innerWidth, height: innerHeight },
};
});
if (
Math.abs(geometry.svg.width - geometry.viewport.width) > 1 ||
Math.abs(geometry.svg.height - geometry.viewport.height) > 1
) {
throw new Error(
`Blockly SVG did not fill ${width}x${height}: ${JSON.stringify(geometry)}`,
);
}
const categories = await page.$$(".blocklyToolboxCategory");
for (let index = 0; index < categories.length; index += 1) {
await categories[index].click();
await page.waitForFunction(
() => {
const flyout = document.querySelector(
".blocklyFlyout.blocklyToolboxFlyout",
);
return flyout && flyout.getBoundingClientRect().width > 0;
},
{ timeout: 3000 },
);
const bounds = await page.evaluate((categoryIndex) => {
const category = document
.querySelectorAll(".blocklyToolboxCategory")
[categoryIndex].getBoundingClientRect();
const flyout = document
.querySelector(".blocklyFlyout.blocklyToolboxFlyout")
.getBoundingClientRect();
return {
category: {
width: category.width,
height: category.height,
lineHeight: getComputedStyle(
document.querySelectorAll(".blocklyToolboxCategory")[
categoryIndex
],
).lineHeight,
marginBottom: getComputedStyle(
document.querySelectorAll(".blocklyToolboxCategory")[
categoryIndex
],
).marginBottom,
},
flyout: {
left: flyout.left,
top: flyout.top,
right: flyout.right,
bottom: flyout.bottom,
},
viewport: { width: innerWidth, height: innerHeight },
};
}, index);
if (
bounds.category.height !== 48 ||
bounds.category.lineHeight !== "48px" ||
bounds.category.marginBottom !== "0px"
) {
throw new Error(
`toolbox category ${index} spacing is wrong: ${JSON.stringify(bounds.category)}`,
);
}
if (
bounds.flyout.left < -1 ||
bounds.flyout.top < -1 ||
bounds.flyout.right > bounds.viewport.width + 1 ||
bounds.flyout.bottom > bounds.viewport.height + 1
) {
throw new Error(
`toolbox flyout ${index} escaped ${width}x${height}: ${JSON.stringify(bounds.flyout)}`,
);
}
}
}
async function assertToolboxTheme(scheme, background, foreground) {
await page.emulateMediaFeatures([
{ name: "prefers-color-scheme", value: scheme },
]);
await page.waitForFunction(
(expectedBackground, expectedForeground) => {
const style = getComputedStyle(
document.querySelector(".blocklyToolbox"),
);
return (
style.backgroundColor === expectedBackground &&
style.color === expectedForeground
);
},
{},
background,
foreground,
);
}
await assertToolboxTheme("light", "rgb(242, 242, 248)", "rgb(27, 27, 31)");
await assertToolboxTheme("dark", "rgb(37, 37, 43)", "rgb(242, 242, 248)");
await assertToolboxTheme("light", "rgb(242, 242, 248)", "rgb(27, 27, 31)");
const gpioTypes = ["pyble_gpio_pin", "pyble_gpio_write", "pyble_gpio_read"];
const gpioContract = await page.evaluate(
({ types, labels }) => {
const mainWorkspace = Blockly.getMainWorkspace();
const toolbox = mainWorkspace.getToolbox();
const gpioCategory = toolbox
.getToolboxItems()
.find(
(item) =>
typeof item.getName === "function" &&
item.getName() === labels.gpioCategory,
);
const gpioContents =
gpioCategory && Array.isArray(gpioCategory.getContents())
? gpioCategory.getContents()
: [];
const toolboxTypes = gpioContents
.filter((item) => item.kind === "block")
.map((item) => item.type);
const pinToolboxItem = gpioContents.find(
(item) => item.kind === "block" && item.type === "pyble_gpio_pin",
);
const definitions = Object.fromEntries(
types.map((type) => [type, Boolean(Blockly.Blocks[type])]),
);
const generators = Object.fromEntries(
types.map((type) => [
type,
typeof python.pythonGenerator.forBlock[type] === "function",
]),
);
let shape = null;
let copy = null;
if (
Object.values(definitions).every(Boolean) &&
Object.values(generators).every(Boolean)
) {
const scratch = new Blockly.Workspace();
try {
const pin = scratch.newBlock("pyble_gpio_pin");
const write = scratch.newBlock("pyble_gpio_write");
const read = scratch.newBlock("pyble_gpio_read");
const checks = (connection) =>
connection && connection.getCheck()
? [...(connection.getCheck() || [])].sort()
: null;
const optionValues = (block, fieldName) => {
const field = block.getField(fieldName);
return field && typeof field.getOptions === "function"
? field
.getOptions(false)
.map((option) => option[1])
.sort()
: null;
};
const optionLabels = (block, fieldName) => {
const field = block.getField(fieldName);
return field && typeof field.getOptions === "function"
? field.getOptions(false).map((option) => option[0])
: null;
};
shape = {
pin: {
gpioCheck: checks(pin.getInput("GPIO")?.connection),
gpioConnected: Boolean(
pin.getInput("GPIO")?.connection.targetConnection,
),
outputCheck: checks(pin.outputConnection),
modes: optionValues(pin, "MODE"),
pulls: optionValues(pin, "PULL"),
},
write: {
pinCheck: checks(write.getInput("PIN")?.connection),
pinConnected: Boolean(
write.getInput("PIN")?.connection.targetConnection,
),
levels: optionValues(write, "LEVEL"),
isStatement: Boolean(
write.previousConnection && write.nextConnection,
),
},
read: {
pinCheck: checks(read.getInput("PIN")?.connection),
pinConnected: Boolean(
read.getInput("PIN")?.connection.targetConnection,
),
outputCheck: checks(read.outputConnection),
},
};
copy = {
pinText: pin.toString(),
pinTooltip: pin.getTooltip(),
modeLabels: optionLabels(pin, "MODE"),
pullLabels: optionLabels(pin, "PULL"),
writeText: write.toString(),
writeTooltip: write.getTooltip(),
levelLabels: optionLabels(write, "LEVEL"),
readText: read.toString(),
readTooltip: read.getTooltip(),
};
} finally {
scratch.dispose();
}
}
return {
categoryFound: Boolean(gpioCategory),
toolboxTypes,
toolboxHasGpioPreset: Boolean(
pinToolboxItem && pinToolboxItem.inputs && pinToolboxItem.inputs.GPIO,
),
definitions,
generators,
shape,
copy,
};
},
{ types: gpioTypes, labels: localizedHostMessages },
);
const gpioContractProblems = [];
if (!gpioContract.categoryFound) {
gpioContractProblems.push(
`missing localized toolbox category "${localizedHostMessages.gpioCategory}"`,
);
}
for (const type of gpioTypes) {
if (!gpioContract.toolboxTypes.includes(type)) {
gpioContractProblems.push(`${type} is absent from the GPIO toolbox`);
}
if (!gpioContract.definitions[type]) {
gpioContractProblems.push(`${type} has no authored block definition`);
}
if (!gpioContract.generators[type]) {
gpioContractProblems.push(`${type} has no MicroPython generator`);
}
}
if (gpioContract.toolboxHasGpioPreset) {
gpioContractProblems.push(
"pyble_gpio_pin supplies a board-specific GPIO shadow/default",
);
}
if (gpioContractProblems.length > 0) {
throw new Error(
`GPIO Blockly contract is incomplete: ${gpioContractProblems.join("; ")}`,
);
}
function assertSameJson(label, actual, expected) {
if (JSON.stringify(actual) !== JSON.stringify(expected)) {
throw new Error(
`${label}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`,
);
}
}
const requiredNeopixelRuntimeTypes = [
"pyble_neopixel_create",
"pyble_neopixel_rgb",
"pyble_neopixel_set_pixel",
"pyble_neopixel_fill",
"pyble_neopixel_write",
];
const missingNeopixelRuntimeTypes = await page.evaluate(
(types) =>
types.filter(
(type) =>
!Blockly.Blocks[type] ||
typeof python.pythonGenerator.forBlock[type] !== "function",
),
requiredNeopixelRuntimeTypes,
);
if (missingNeopixelRuntimeTypes.length > 0) {
throw new Error(
"NeoPixel Blockly runtime is missing definitions/generators: " +
missingNeopixelRuntimeTypes.join(", "),
);
}
assertSameJson(
"pyble_gpio_pin connection and dropdown contract",
gpioContract.shape.pin,
{
gpioCheck: ["Number"],
gpioConnected: false,
outputCheck: ["Pin"],
modes: ["IN", "OUT"],
pulls: ["DOWN", "NONE", "UP"],
},
);
assertSameJson(
"pyble_gpio_write connection and dropdown contract",
gpioContract.shape.write,
{
pinCheck: ["Pin"],
pinConnected: false,
levels: ["HIGH", "LOW"],
isStatement: true,
},
);
assertSameJson(
"pyble_gpio_read connection contract",
gpioContract.shape.read,
{
pinCheck: ["Pin"],
pinConnected: false,
outputCheck: ["Number"],
},
);
assertSameJson("localized GPIO mode labels", gpioContract.copy.modeLabels, [
localizedHostMessages.gpioModeInput,
localizedHostMessages.gpioModeOutput,
]);
assertSameJson("localized GPIO pull labels", gpioContract.copy.pullLabels, [
localizedHostMessages.gpioPullNone,
localizedHostMessages.gpioPullUp,
localizedHostMessages.gpioPullDown,
]);
assertSameJson("localized GPIO level labels", gpioContract.copy.levelLabels, [
localizedHostMessages.gpioLevelLow,
localizedHostMessages.gpioLevelHigh,
]);
assertSameJson(
"localized GPIO pin tooltip",
gpioContract.copy.pinTooltip,
localizedHostMessages.gpioPinTooltip,
);
assertSameJson(
"localized GPIO write tooltip",
gpioContract.copy.writeTooltip,
localizedHostMessages.gpioWriteTooltip,
);
assertSameJson(
"localized GPIO read tooltip",
gpioContract.copy.readTooltip,
localizedHostMessages.gpioReadTooltip,
);
for (const [label, actual, markers] of [
[
"GPIO pin block message",
gpioContract.copy.pinText,
["BROCHE-LOCALE", "MODE-LOCAL", "TIRAGE-LOCAL"],
],
[
"GPIO write block message",
gpioContract.copy.writeText,
["ÉCRIRE-LOCAL", "NIVEAU-LOCAL"],
],
["GPIO read block message", gpioContract.copy.readText, ["LIRE-LOCAL"]],
]) {
for (const marker of markers) {
if (!actual.includes(marker)) {
throw new Error(
`${label} did not render injected copy "${marker}": ${JSON.stringify(actual)}`,
);
}
}
}
async function restoreWorkspace(state, priorRevision) {
const result = await page.evaluate(
({ workspaceState, baseRevision }) => {
const firstMessage = window.__pybleMessages.length;
const accepted = window.pybleBlocks.restore(
JSON.stringify(workspaceState),
baseRevision,
);
return {
accepted,
messages: window.__pybleMessages.slice(firstMessage),
};
},
{ workspaceState: state, baseRevision: priorRevision },
);
if (!result.accepted) {
throw new Error("the public Blockly restore bridge rejected valid JSON");
}
if (result.messages.length === 0) {
throw new Error("the public Blockly restore bridge emitted no result");
}
return result.messages[result.messages.length - 1];
}
// Beginner examples are ordinary Blockly serialization. The catalog never
// stores generated source: these checks materialize explicit test-only GPIO
// choices, then ask the real pinned generator for the exact Python.
const examplesCatalog = JSON.parse(
fs.readFileSync(
path.join(repoRoot, "app/assets/blockly/examples/catalog.json"),
"utf8",
),
);
const expectedExampleIds = [
"hello-pyble",
"count-repeatedly",
"blink-led",
"blink-neopixel",
"read-button",
"button-controls-led",
"reusable-function",
];
assertSameJson(
"beginner example catalog IDs",
examplesCatalog.examples.map((example) => example.id),
expectedExampleIds,
);
const examplesToolboxContract = await page.evaluate(
({ ids, labels }) => {
const mainWorkspace = Blockly.getMainWorkspace();
const configurable =
typeof window.pybleBlocks.configureHost === "function";
const category = mainWorkspace
.getToolbox()
.getToolboxItems()
.find(
(item) =>
typeof item.getName === "function" &&
item.getName() === labels.examplesCategory,
);
const contents =
category && Array.isArray(category.getContents())
? category.getContents()
: [];
const buttons = contents.filter((item) => item.kind === "button");
const callbackKeys = buttons.map((item) => item.callbackKey);
const callbacksReady = callbackKeys.every(
(key) => typeof mainWorkspace.getButtonCallback(key) === "function",
);
const before = window.__pybleMessages.length;
if (callbacksReady && callbackKeys.length === ids.length) {
mainWorkspace.getButtonCallback(callbackKeys[2])();
}
return {
configurable,
categoryFound: Boolean(category),
buttonTexts: buttons.map((item) => item.text),
callbackKeys,
callbacksReady,
request: window.__pybleMessages.slice(before).at(-1),
};
},
{ ids: expectedExampleIds, labels: localizedHostMessages },
);
assertSameJson("Examples toolbox bridge", examplesToolboxContract, {
configurable: true,
categoryFound: true,
buttonTexts: expectedExampleIds.map(
(id) => localizedHostMessages.exampleTitles[id],
),
callbackKeys: expectedExampleIds.map((id) => `PYBLE_EXAMPLE_${id}`),
callbacksReady: true,
request: {
version: 1,
type: "openExamples",
exampleId: "blink-led",
hostEpoch,
},
});
const timeContract = await page.evaluate((timeCategoryLabel) => {
const mainWorkspace = Blockly.getMainWorkspace();
const category = mainWorkspace
.getToolbox()
.getToolboxItems()
.find(
(item) =>
typeof item.getName === "function" &&
item.getName() === timeCategoryLabel,
);
const contents =
category && Array.isArray(category.getContents())
? category.getContents()
: [];
const item = contents.find(
(value) => value.kind === "block" && value.type === "pyble_time_sleep_ms",
);
const scratch = new Blockly.Workspace();
try {
const first = scratch.newBlock("pyble_time_sleep_ms");
const second = scratch.newBlock("pyble_time_sleep_ms");
const number = (value) => {
const block = scratch.newBlock("math_number");
block.setFieldValue(value, "NUM");
return block;
};
first
.getInput("MILLISECONDS")
.connection.connect(number(250).outputConnection);
second
.getInput("MILLISECONDS")
.connection.connect(number(1000).outputConnection);
first.nextConnection.connect(second.previousConnection);
return {
categoryFound: Boolean(category),
toolboxFound: Boolean(item),
toolboxHasDefault: Boolean(item && item.inputs),
inputCheck: first.getInput("MILLISECONDS").connection.getCheck() || [],
isStatement: Boolean(first.previousConnection && first.nextConnection),
source: python.pythonGenerator.workspaceToCode(scratch),
};
} finally {
scratch.dispose();
}
}, localizedHostMessages.timeCategory);
assertSameJson("sleep_ms runtime shape", timeContract, {
categoryFound: true,
toolboxFound: true,
toolboxHasDefault: false,
inputCheck: ["Number"],
isStatement: true,
source:
"from time import sleep_ms\n\n\n" +
"sleep_ms(250)\n" +
"sleep_ms(1000)\n",
});
const promptHelperSource = await page.evaluate(() => {
const scratch = new Blockly.Workspace();
try {
const prompt = scratch.newBlock("text_prompt_ext");
prompt.setFieldValue("TEXT", "TYPE");
const message = scratch.newBlock("text");
message.setFieldValue("Prompt", "TEXT");
prompt.getInput("TEXT").connection.connect(message.outputConnection);
return python.pythonGenerator.workspaceToCode(scratch);
} finally {
scratch.dispose();
}
});
if (
!promptHelperSource.includes(" try:\n") ||
!promptHelperSource.includes(" except NameError:\n") ||
promptHelperSource.includes('${"try"}')
) {
throw new Error(
`normalized Python helper changed at runtime:\n${promptHelperSource}`,
);
}
const invalidTimeValues = await page.evaluate(() => {
const rejects = (value, connected = true) => {
const scratch = new Blockly.Workspace();
try {
const sleep = scratch.newBlock("pyble_time_sleep_ms");
if (connected) {
const number = scratch.newBlock("math_number");
number.setFieldValue(value, "NUM");
sleep
.getInput("MILLISECONDS")
.connection.connect(number.outputConnection);
}
try {
python.pythonGenerator.workspaceToCode(scratch);
return null;
} catch (error) {
return error instanceof Error ? error.message : String(error);
}
} finally {
scratch.dispose();
}
};
return {
missing: rejects(0, false),
negative: rejects(-1),
fractional: rejects(1.5),
};
});
assertSameJson("sleep_ms rejects invalid literals", invalidTimeValues, {
missing: localizedHostMessages.timeRequiredError,
negative: localizedHostMessages.timeInvalidError,
fractional: localizedHostMessages.timeInvalidError,
});
const neopixelTypes = [
"pyble_neopixel_create",
"pyble_neopixel_rgb",
"pyble_neopixel_set_pixel",
"pyble_neopixel_fill",
"pyble_neopixel_write",
];
const neopixelContract = await page.evaluate(
({ types, labels }) => {
const mainWorkspace = Blockly.getMainWorkspace();
const category = mainWorkspace
.getToolbox()
.getToolboxItems()
.find(
(item) =>
typeof item.getName === "function" &&
item.getName() === labels.neopixelCategory,
);
const contents =
category && Array.isArray(category.getContents())
? category.getContents()
: [];
const toolboxBlocks = contents.filter((item) => item.kind === "block");
const definitions = Object.fromEntries(
types.map((type) => [type, Boolean(Blockly.Blocks[type])]),
);
const generators = Object.fromEntries(
types.map((type) => [
type,
typeof python.pythonGenerator.forBlock[type] === "function",
]),
);
if (
!Object.values(definitions).every(Boolean) ||
!Object.values(generators).every(Boolean)
) {
return {
categoryFound: Boolean(category),
toolboxTypes: toolboxBlocks.map((item) => item.type),
toolboxHasDefaults: toolboxBlocks.some((item) => item.inputs),
definitions,
generators,
shape: null,
copy: null,
};
}
const scratch = new Blockly.Workspace();
try {
const create = scratch.newBlock("pyble_neopixel_create");
const rgb = scratch.newBlock("pyble_neopixel_rgb");
const setPixel = scratch.newBlock("pyble_neopixel_set_pixel");
const fill = scratch.newBlock("pyble_neopixel_fill");
const write = scratch.newBlock("pyble_neopixel_write");
const checks = (connection) =>
connection && connection.getCheck
? [...(connection.getCheck() || [])].sort()
: null;
const disconnected = (block, inputName) =>
!block.getInput(inputName)?.connection.targetConnection;
return {
categoryFound: Boolean(category),
toolboxTypes: toolboxBlocks.map((item) => item.type),
toolboxHasDefaults: toolboxBlocks.some((item) => item.inputs),
definitions,
generators,
shape: {
create: {
pinCheck: checks(create.getInput("PIN")?.connection),
pixelsCheck: checks(create.getInput("PIXELS")?.connection),
outputCheck: checks(create.outputConnection),
disconnected:
disconnected(create, "PIN") && disconnected(create, "PIXELS"),
},
rgb: {
redCheck: checks(rgb.getInput("RED")?.connection),
greenCheck: checks(rgb.getInput("GREEN")?.connection),
blueCheck: checks(rgb.getInput("BLUE")?.connection),
outputCheck: checks(rgb.outputConnection),
disconnected:
disconnected(rgb, "RED") &&
disconnected(rgb, "GREEN") &&
disconnected(rgb, "BLUE"),
},
setPixel: {
stripCheck: checks(setPixel.getInput("STRIP")?.connection),
indexCheck: checks(setPixel.getInput("INDEX")?.connection),
colorCheck: checks(setPixel.getInput("COLOR")?.connection),
isStatement: Boolean(
setPixel.previousConnection && setPixel.nextConnection,
),
disconnected:
disconnected(setPixel, "STRIP") &&
disconnected(setPixel, "INDEX") &&
disconnected(setPixel, "COLOR"),
},
fill: {
stripCheck: checks(fill.getInput("STRIP")?.connection),
colorCheck: checks(fill.getInput("COLOR")?.connection),
isStatement: Boolean(
fill.previousConnection && fill.nextConnection,
),
disconnected:
disconnected(fill, "STRIP") && disconnected(fill, "COLOR"),
},
write: {
stripCheck: checks(write.getInput("STRIP")?.connection),
isStatement: Boolean(
write.previousConnection && write.nextConnection,
),
disconnected: disconnected(write, "STRIP"),
},
},
copy: {
createText: create.toString(),
rgbText: rgb.toString(),
setPixelText: setPixel.toString(),
fillText: fill.toString(),
writeText: write.toString(),
tooltips: [
create.getTooltip(),
rgb.getTooltip(),
setPixel.getTooltip(),
fill.getTooltip(),
write.getTooltip(),
],
},
};
} finally {
scratch.dispose();
}
},
{ types: neopixelTypes, labels: localizedHostMessages },
);
const neopixelContractProblems = [];
if (!neopixelContract.categoryFound) {
neopixelContractProblems.push(
`missing localized toolbox category "${localizedHostMessages.neopixelCategory}"`,
);
}
if (
JSON.stringify(neopixelContract.toolboxTypes) !==
JSON.stringify(neopixelTypes)
) {
neopixelContractProblems.push(
`expected exactly ${JSON.stringify(neopixelTypes)} in the toolbox, got ${JSON.stringify(neopixelContract.toolboxTypes)}`,
);
}
for (const type of neopixelTypes) {
if (!neopixelContract.definitions[type]) {
neopixelContractProblems.push(`${type} has no block definition`);
}
if (!neopixelContract.generators[type]) {
neopixelContractProblems.push(`${type} has no Python generator`);
}
}
if (neopixelContract.toolboxHasDefaults) {
neopixelContractProblems.push(
"NeoPixel toolbox blocks contain a shadow/default",
);
}
if (neopixelContractProblems.length > 0) {
throw new Error(
`NeoPixel Blockly contract is incomplete: ${neopixelContractProblems.join("; ")}`,
);
}
assertSameJson("NeoPixel block connection contract", neopixelContract.shape, {
create: {
pinCheck: ["Pin"],
pixelsCheck: ["Number"],
outputCheck: ["NeoPixel"],
disconnected: true,
},
rgb: {
redCheck: ["Number"],
greenCheck: ["Number"],
blueCheck: ["Number"],
outputCheck: ["NeoPixelColor"],
disconnected: true,
},
setPixel: {
stripCheck: ["NeoPixel"],
indexCheck: ["Number"],
colorCheck: ["NeoPixelColor"],
isStatement: true,
disconnected: true,
},
fill: {
stripCheck: ["NeoPixel"],
colorCheck: ["NeoPixelColor"],
isStatement: true,
disconnected: true,
},
write: {
stripCheck: ["NeoPixel"],
isStatement: true,
disconnected: true,
},
});
assertSameJson(
"localized NeoPixel tooltips",
neopixelContract.copy.tooltips,
[
localizedHostMessages.neopixelCreateTooltip,
localizedHostMessages.neopixelRgbTooltip,
localizedHostMessages.neopixelSetPixelTooltip,
localizedHostMessages.neopixelFillTooltip,
localizedHostMessages.neopixelWriteTooltip,
],
);
for (const [label, actual, marker] of [
[
"NeoPixel create block message",
neopixelContract.copy.createText,
"CRÉER-PIXEL-LOCAL",
],
[
"NeoPixel RGB block message",
neopixelContract.copy.rgbText,
"COULEUR-LOCALE",
],
[
"NeoPixel set block message",
neopixelContract.copy.setPixelText,
"RÉGLER-PIXEL-LOCAL",
],
[
"NeoPixel fill block message",
neopixelContract.copy.fillText,
"REMPLIR-PIXELS-LOCAL",
],