plainscript-lang 0.1.7 → 1.0.0
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.
- package/README.md +97 -39
- package/compiler/bundler.js +1 -1
- package/compiler/cli.js +44 -42
- package/compiler/generator.js +826 -16
- package/compiler/lexer.js +31 -2
- package/compiler/parser.js +548 -22
- package/compiler/version.js +1 -1
- package/docs/CAPABILITY_GAP_AUDIT.md +439 -0
- package/docs/PLINJS_SPEC.md +124 -24
- package/docs/index.html +535 -2205
- package/docs/website/script.js +889 -133
- package/docs/website/style.css +652 -1113
- package/examples/auth-api.ps +56 -0
- package/examples/{cache-and-jobs.pln → cache-and-jobs.ps} +1 -1
- package/examples/concurrency.ps +49 -0
- package/examples/{database.pln → database.ps} +1 -1
- package/examples/{deployment.pln → deployment.ps} +1 -1
- package/examples/{email-send.pln → email-send.ps} +1 -1
- package/examples/error-handling.ps +54 -0
- package/examples/file-uploads.ps +39 -0
- package/examples/files-and-config.ps +47 -0
- package/examples/http-client.ps +44 -0
- package/examples/modules/app.ps +16 -0
- package/examples/modules/math.ps +20 -0
- package/examples/record-kinds.ps +43 -0
- package/examples/{rest-api.pln → rest-api.ps} +1 -1
- package/examples/{scheduled-tasks.pln → scheduled-tasks.ps} +1 -1
- package/examples/search-and-filter.ps +34 -0
- package/examples/sessions-and-cookies.ps +54 -0
- package/examples/{websocket-server.pln → websocket-server.ps} +1 -1
- package/package.json +2 -2
- package/docs/website/index.html +0 -1500
- /package/examples/{arrays.pln → arrays.ps} +0 -0
- /package/examples/{day2.pln → day2.ps} +0 -0
- /package/examples/{day3.pln → day3.ps} +0 -0
- /package/examples/{expressions.pln → expressions.ps} +0 -0
- /package/examples/football-backend/{app.pln → app.ps} +0 -0
- /package/examples/{hello.pln → hello.ps} +0 -0
- /package/examples/id-verification/{app.pln → app.ps} +0 -0
- /package/examples/{loops.pln → loops.ps} +0 -0
- /package/examples/{objects.pln → objects.ps} +0 -0
- /package/examples/{rest-api-fetch.pln → rest-api-fetch.ps} +0 -0
- /package/examples/{server.pln → server.ps} +0 -0
- /package/examples/{start.pln → start.ps} +0 -0
- /package/examples/{stdlib.pln → stdlib.ps} +0 -0
- /package/examples/{telegram-bot.pln → telegram-bot.ps} +0 -0
- /package/examples/{web-app.pln → web-app.ps} +0 -0
- /package/examples/whatsapp-bot/{pairing.pln → pairing.ps} +0 -0
- /package/examples/whatsapp-bot/{qr.pln → qr.ps} +0 -0
package/docs/website/script.js
CHANGED
|
@@ -1,197 +1,953 @@
|
|
|
1
|
-
|
|
1
|
+
function initSyntaxHighlighting() {
|
|
2
|
+
var codeBlocks = document.querySelectorAll('.code-window-body code, .code-block code, .code-block--wide code');
|
|
3
|
+
|
|
4
|
+
var PS_KEYWORDS = {
|
|
5
|
+
'use':1,'server':1,'when':1,'someone':1,'asks':1,'for':1,'send':1,'log':1,
|
|
6
|
+
'save':1,'as':1,'if':1,'else':1,'then':1,'end':1,'function':1,'returns':1,
|
|
7
|
+
'return':1,'database':1,'query':1,'insert':1,'into':1,'values':1,'each':1,
|
|
8
|
+
'in':1,'while':1,'let':1,'be':1,'not':1,'and':1,'or':1,'equals':1,'greater':1,
|
|
9
|
+
'less':1,'than':1,'true':1,'false':1,'null':1,'none':1,'javascript':1,
|
|
10
|
+
'import':1,'from':1,'export':1,'class':1,'new':1,'this':1,'with':1,'do':1,
|
|
11
|
+
'try':1,'catch':1,'throw':1,'async':1,'await':1
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
var JS_KEYWORDS = {
|
|
15
|
+
'const':1,'let':1,'var':1,'function':1,'return':1,'if':1,'else':1,'for':1,
|
|
16
|
+
'while':1,'do':1,'switch':1,'case':1,'break':1,'continue':1,'new':1,'this':1,
|
|
17
|
+
'class':1,'extends':1,'import':1,'from':1,'export':1,'default':1,'try':1,
|
|
18
|
+
'catch':1,'throw':1,'async':1,'await':1,'typeof':1,'instanceof':1,'in':1,
|
|
19
|
+
'of':1,'true':1,'false':1,'null':1,'undefined':1,'void':1
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
var JS_BUILTINS = {
|
|
23
|
+
'console':1,'require':1,'module':1,'exports':1,'Math':1,'JSON':1,'Promise':1,
|
|
24
|
+
'Array':1,'Object':1,'String':1,'Number':1,'Boolean':1,'Date':1,'RegExp':1,
|
|
25
|
+
'Error':1,'Map':1,'Set':1
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
var OPERATORS = [
|
|
29
|
+
'===','!==','=>','>=','<=','&&','||','++','--',
|
|
30
|
+
'=','>','<','+','-','*','/','%','!'
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
function esc(ch) {
|
|
34
|
+
if (ch === '&') return '&';
|
|
35
|
+
if (ch === '<') return '<';
|
|
36
|
+
if (ch === '>') return '>';
|
|
37
|
+
if (ch === '"') return '"';
|
|
38
|
+
if (ch === "'") return ''';
|
|
39
|
+
return ch;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function escStr(s) {
|
|
43
|
+
var out = '';
|
|
44
|
+
for (var k = 0; k < s.length; k++) {
|
|
45
|
+
out += esc(s[k]);
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function span(cls, text) {
|
|
51
|
+
return '<span class="token ' + cls + '">' + text + '</span>';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function tokenize(code, lang) {
|
|
55
|
+
var isPS = lang === 'plainscript';
|
|
56
|
+
var keywords = isPS ? PS_KEYWORDS : JS_KEYWORDS;
|
|
57
|
+
var builtins = isPS ? null : JS_BUILTINS;
|
|
58
|
+
|
|
59
|
+
var i = 0;
|
|
60
|
+
var len = code.length;
|
|
61
|
+
var out = '';
|
|
62
|
+
|
|
63
|
+
while (i < len) {
|
|
64
|
+
var ch = code[i];
|
|
65
|
+
|
|
66
|
+
// --- Template literals (JS only) ---
|
|
67
|
+
if (!isPS && ch === '`') {
|
|
68
|
+
var tplStart = i;
|
|
69
|
+
i++;
|
|
70
|
+
var tplContent = '`';
|
|
71
|
+
while (i < len && code[i] !== '`') {
|
|
72
|
+
if (code[i] === '\\') {
|
|
73
|
+
tplContent += code[i];
|
|
74
|
+
i++;
|
|
75
|
+
if (i < len) {
|
|
76
|
+
tplContent += code[i];
|
|
77
|
+
i++;
|
|
78
|
+
}
|
|
79
|
+
} else {
|
|
80
|
+
tplContent += code[i];
|
|
81
|
+
i++;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (i < len) {
|
|
85
|
+
tplContent += '`';
|
|
86
|
+
i++;
|
|
87
|
+
}
|
|
88
|
+
out += span('string', escStr(tplContent));
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// --- Strings ---
|
|
93
|
+
if (ch === '"' || ch === "'") {
|
|
94
|
+
var q = ch;
|
|
95
|
+
var strStart = i;
|
|
96
|
+
i++;
|
|
97
|
+
var strContent = q;
|
|
98
|
+
while (i < len && code[i] !== q) {
|
|
99
|
+
if (code[i] === '\\' && i + 1 < len) {
|
|
100
|
+
strContent += code[i];
|
|
101
|
+
i++;
|
|
102
|
+
strContent += code[i];
|
|
103
|
+
i++;
|
|
104
|
+
} else if (code[i] === '\n') {
|
|
105
|
+
break;
|
|
106
|
+
} else {
|
|
107
|
+
strContent += code[i];
|
|
108
|
+
i++;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (i < len && code[i] === q) {
|
|
112
|
+
strContent += code[i];
|
|
113
|
+
i++;
|
|
114
|
+
}
|
|
115
|
+
out += span('string', escStr(strContent));
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// --- Single-line comments ---
|
|
120
|
+
if (ch === '/' && i + 1 < len && code[i + 1] === '/') {
|
|
121
|
+
var commentEnd = i;
|
|
122
|
+
while (commentEnd < len && code[commentEnd] !== '\n') {
|
|
123
|
+
commentEnd++;
|
|
124
|
+
}
|
|
125
|
+
var comment = code.substring(i, commentEnd);
|
|
126
|
+
out += span('comment', escStr(comment));
|
|
127
|
+
i = commentEnd;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// --- Multi-line comments ---
|
|
132
|
+
if (!isPS && ch === '/' && i + 1 < len && code[i + 1] === '*') {
|
|
133
|
+
var mEnd = i + 2;
|
|
134
|
+
while (mEnd < len) {
|
|
135
|
+
if (mEnd < len - 1 && code[mEnd] === '*' && code[mEnd + 1] === '/') {
|
|
136
|
+
mEnd += 2;
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
mEnd++;
|
|
140
|
+
}
|
|
141
|
+
var mComment = code.substring(i, mEnd);
|
|
142
|
+
out += span('comment', escStr(mComment));
|
|
143
|
+
i = mEnd;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// --- Hex numbers (JS only) ---
|
|
148
|
+
if (!isPS && ch === '0' && i + 1 < len && (code[i + 1] === 'x' || code[i + 1] === 'X')) {
|
|
149
|
+
var hexStart = i;
|
|
150
|
+
i += 2;
|
|
151
|
+
while (i < len && /[0-9a-fA-F]/.test(code[i])) {
|
|
152
|
+
i++;
|
|
153
|
+
}
|
|
154
|
+
var hex = code.substring(hexStart, i);
|
|
155
|
+
out += span('number', escStr(hex));
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// --- Numbers ---
|
|
160
|
+
if (/[0-9]/.test(ch)) {
|
|
161
|
+
var numStart = i;
|
|
162
|
+
while (i < len && /[0-9]/.test(code[i])) {
|
|
163
|
+
i++;
|
|
164
|
+
}
|
|
165
|
+
if (i < len && code[i] === '.' && i + 1 < len && /[0-9]/.test(code[i + 1])) {
|
|
166
|
+
i++;
|
|
167
|
+
while (i < len && /[0-9]/.test(code[i])) {
|
|
168
|
+
i++;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
var num = code.substring(numStart, i);
|
|
172
|
+
out += span('number', escStr(num));
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// --- Words (identifiers, keywords, builtins) ---
|
|
177
|
+
if (/[a-zA-Z_$]/.test(ch)) {
|
|
178
|
+
var wordStart = i;
|
|
179
|
+
while (i < len && /[a-zA-Z0-9_$]/.test(code[i])) {
|
|
180
|
+
i++;
|
|
181
|
+
}
|
|
182
|
+
var word = code.substring(wordStart, i);
|
|
183
|
+
|
|
184
|
+
// Look ahead for function call
|
|
185
|
+
var j = i;
|
|
186
|
+
while (j < len && (code[j] === ' ' || code[j] === '\t')) {
|
|
187
|
+
j++;
|
|
188
|
+
}
|
|
189
|
+
var isFuncCall = j < len && code[j] === '(';
|
|
190
|
+
|
|
191
|
+
// Check for property access (preceded by a dot)
|
|
192
|
+
var lookBehind = wordStart - 1;
|
|
193
|
+
while (lookBehind >= 0 && (code[lookBehind] === ' ' || code[lookBehind] === '\t')) {
|
|
194
|
+
lookBehind--;
|
|
195
|
+
}
|
|
196
|
+
var isProperty = lookBehind >= 0 && code[lookBehind] === '.';
|
|
197
|
+
|
|
198
|
+
if (keywords[word]) {
|
|
199
|
+
out += span('keyword', escStr(word));
|
|
200
|
+
} else if (builtins && builtins[word]) {
|
|
201
|
+
out += span('builtin', escStr(word));
|
|
202
|
+
} else if (isProperty) {
|
|
203
|
+
out += span('property', escStr(word));
|
|
204
|
+
} else if (isFuncCall) {
|
|
205
|
+
out += span('function', escStr(word));
|
|
206
|
+
} else {
|
|
207
|
+
out += span('default', escStr(word));
|
|
208
|
+
}
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// --- Operators ---
|
|
213
|
+
var matchedOp = '';
|
|
214
|
+
for (var oi = 0; oi < OPERATORS.length; oi++) {
|
|
215
|
+
var op = OPERATORS[oi];
|
|
216
|
+
if (code.indexOf(op, i) === i && op.length > matchedOp.length) {
|
|
217
|
+
matchedOp = op;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (matchedOp) {
|
|
221
|
+
out += span('operator', escStr(matchedOp));
|
|
222
|
+
i += matchedOp.length;
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// --- Punctuation ---
|
|
227
|
+
if ('(){}[];,'.indexOf(ch) !== -1) {
|
|
228
|
+
out += span('punctuation', esc(ch));
|
|
229
|
+
i++;
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// --- Dot (JS property access) ---
|
|
234
|
+
if (!isPS && ch === '.') {
|
|
235
|
+
out += span('punctuation', '.');
|
|
236
|
+
i++;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// --- Anything else (whitespace, newlines, unknown) ---
|
|
241
|
+
var wsStart = i;
|
|
242
|
+
while (i < len) {
|
|
243
|
+
var wc = code[i];
|
|
244
|
+
if (/[a-zA-Z0-9_$'"`]/.test(wc)) break;
|
|
245
|
+
if (wc === '/' && i + 1 < len && (code[i + 1] === '/' || code[i + 1] === '*')) break;
|
|
246
|
+
if (wc === '\\' && !isPS) break;
|
|
247
|
+
if ('(){}[];,'.indexOf(wc) !== -1) break;
|
|
248
|
+
if ('=<>+-*/%!&|^~?'.indexOf(wc) !== -1) break;
|
|
249
|
+
i++;
|
|
250
|
+
}
|
|
251
|
+
if (i > wsStart) {
|
|
252
|
+
out += escStr(code.substring(wsStart, i));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
for (var i = 0; i < codeBlocks.length; i++) {
|
|
260
|
+
var codeEl = codeBlocks[i];
|
|
261
|
+
var text = codeEl.textContent;
|
|
262
|
+
if (!text.trim()) continue;
|
|
263
|
+
|
|
264
|
+
var win = codeEl.closest('.code-window');
|
|
265
|
+
var lang = 'plainscript';
|
|
266
|
+
if (win) {
|
|
267
|
+
var title = win.querySelector('.code-window-title');
|
|
268
|
+
if (title) {
|
|
269
|
+
var titleText = title.textContent.toLowerCase();
|
|
270
|
+
if (titleText.indexOf('plain') === -1) {
|
|
271
|
+
lang = 'javascript';
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (!win) {
|
|
277
|
+
lang = 'plainscript';
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
codeEl.innerHTML = tokenize(text, lang);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function initThreeBackground() {
|
|
285
|
+
var canvas = document.getElementById('bg-canvas');
|
|
286
|
+
if (!canvas || typeof THREE === 'undefined') return;
|
|
287
|
+
|
|
288
|
+
var scene = new THREE.Scene();
|
|
289
|
+
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
|
|
290
|
+
var renderer = new THREE.WebGLRenderer({ canvas: canvas, alpha: true, antialias: true });
|
|
291
|
+
renderer.setSize(window.innerWidth, window.innerHeight);
|
|
292
|
+
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
|
293
|
+
|
|
294
|
+
camera.position.z = 30;
|
|
295
|
+
|
|
296
|
+
var particleCount = 1500;
|
|
297
|
+
var geometry = new THREE.BufferGeometry();
|
|
298
|
+
var positions = new Float32Array(particleCount * 3);
|
|
299
|
+
var sizes = new Float32Array(particleCount);
|
|
300
|
+
|
|
301
|
+
for (var i = 0; i < particleCount; i++) {
|
|
302
|
+
var i3 = i * 3;
|
|
303
|
+
var radius = 50 + Math.random() * 50;
|
|
304
|
+
var theta = Math.random() * Math.PI * 2;
|
|
305
|
+
var phi = Math.acos(2 * Math.random() - 1);
|
|
306
|
+
|
|
307
|
+
positions[i3] = radius * Math.sin(phi) * Math.cos(theta);
|
|
308
|
+
positions[i3 + 1] = radius * Math.sin(phi) * Math.sin(theta);
|
|
309
|
+
positions[i3 + 2] = radius * Math.cos(phi);
|
|
310
|
+
|
|
311
|
+
sizes[i] = 0.5 + Math.random() * 1.5;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
|
|
315
|
+
geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
|
|
316
|
+
|
|
317
|
+
var material = new THREE.PointsMaterial({
|
|
318
|
+
color: 0x10b981,
|
|
319
|
+
size: 0.15,
|
|
320
|
+
transparent: true,
|
|
321
|
+
opacity: 0.6,
|
|
322
|
+
blending: THREE.AdditiveBlending,
|
|
323
|
+
depthWrite: false,
|
|
324
|
+
sizeAttenuation: true
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
var particles = new THREE.Points(geometry, material);
|
|
328
|
+
scene.add(particles);
|
|
329
|
+
|
|
330
|
+
var mouse = { x: 0, y: 0 };
|
|
331
|
+
var targetMouse = { x: 0, y: 0 };
|
|
332
|
+
|
|
333
|
+
document.addEventListener('mousemove', function(e) {
|
|
334
|
+
targetMouse.x = (e.clientX / window.innerWidth - 0.5) * 2;
|
|
335
|
+
targetMouse.y = (e.clientY / window.innerHeight - 0.5) * 2;
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
window.addEventListener('resize', function() {
|
|
339
|
+
camera.aspect = window.innerWidth / window.innerHeight;
|
|
340
|
+
camera.updateProjectionMatrix();
|
|
341
|
+
renderer.setSize(window.innerWidth, window.innerHeight);
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
function animate() {
|
|
345
|
+
requestAnimationFrame(animate);
|
|
346
|
+
|
|
347
|
+
particles.rotation.y += 0.0003;
|
|
348
|
+
particles.rotation.x += 0.0001;
|
|
349
|
+
|
|
350
|
+
mouse.x += (targetMouse.x - mouse.x) * 0.02;
|
|
351
|
+
mouse.y += (targetMouse.y - mouse.y) * 0.02;
|
|
352
|
+
|
|
353
|
+
particles.rotation.y += mouse.x * 0.0005;
|
|
354
|
+
particles.rotation.x += mouse.y * 0.0005;
|
|
355
|
+
|
|
356
|
+
renderer.render(scene, camera);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
animate();
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function initMobileMenu() {
|
|
363
|
+
var hamburger = document.getElementById('nav-hamburger');
|
|
364
|
+
var menu = document.getElementById('mobile-menu');
|
|
365
|
+
if (!hamburger || !menu) return;
|
|
366
|
+
|
|
367
|
+
function openMenu() {
|
|
368
|
+
hamburger.classList.add('open');
|
|
369
|
+
menu.classList.add('open');
|
|
370
|
+
document.body.classList.add('menu-open');
|
|
371
|
+
hamburger.querySelector('i').classList.remove('fa-bars');
|
|
372
|
+
hamburger.querySelector('i').classList.add('fa-xmark');
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function closeMenu() {
|
|
376
|
+
hamburger.classList.remove('open');
|
|
377
|
+
menu.classList.remove('open');
|
|
378
|
+
document.body.classList.remove('menu-open');
|
|
379
|
+
hamburger.querySelector('i').classList.remove('fa-xmark');
|
|
380
|
+
hamburger.querySelector('i').classList.add('fa-bars');
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function toggleMenu() {
|
|
384
|
+
if (menu.classList.contains('open')) {
|
|
385
|
+
closeMenu();
|
|
386
|
+
} else {
|
|
387
|
+
openMenu();
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
hamburger.addEventListener('click', toggleMenu);
|
|
392
|
+
|
|
393
|
+
var mobileLinks = menu.querySelectorAll('a');
|
|
394
|
+
for (var i = 0; i < mobileLinks.length; i++) {
|
|
395
|
+
mobileLinks[i].addEventListener('click', closeMenu);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
document.addEventListener('keydown', function(e) {
|
|
399
|
+
if (e.key === 'Escape' && menu.classList.contains('open')) {
|
|
400
|
+
closeMenu();
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
window.addEventListener('resize', function() {
|
|
405
|
+
if (window.innerWidth > 800 && menu.classList.contains('open')) {
|
|
406
|
+
closeMenu();
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
}
|
|
2
410
|
|
|
3
|
-
/* ── Copy buttons ────────────────────────────────────────────────────────── */
|
|
4
411
|
function initCopyButtons() {
|
|
5
|
-
document.querySelectorAll('.code-copy')
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
412
|
+
var buttons = document.querySelectorAll('.code-copy, .copy-btn');
|
|
413
|
+
for (var i = 0; i < buttons.length; i++) {
|
|
414
|
+
buttons[i].addEventListener('click', function() {
|
|
415
|
+
var btn = this;
|
|
416
|
+
var target = btn.closest('.code-window') || btn.closest('.code-block');
|
|
417
|
+
if (!target) return;
|
|
418
|
+
|
|
419
|
+
var codeEl = target.querySelector('pre code') || target.querySelector('code') || target.querySelector('pre');
|
|
420
|
+
if (!codeEl) return;
|
|
421
|
+
|
|
422
|
+
var text = codeEl.textContent;
|
|
423
|
+
|
|
424
|
+
navigator.clipboard.writeText(text).then(function() {
|
|
425
|
+
var originalHTML = btn.innerHTML;
|
|
426
|
+
btn.innerHTML = '<i class="fas fa-check"></i> Copied';
|
|
15
427
|
btn.classList.add('copied');
|
|
16
|
-
|
|
428
|
+
|
|
429
|
+
setTimeout(function() {
|
|
17
430
|
btn.innerHTML = originalHTML;
|
|
18
431
|
btn.classList.remove('copied');
|
|
19
432
|
}, 2000);
|
|
20
|
-
})
|
|
21
|
-
|
|
22
|
-
|
|
433
|
+
}).catch(function() {
|
|
434
|
+
var textarea = document.createElement('textarea');
|
|
435
|
+
textarea.value = text;
|
|
436
|
+
textarea.style.position = 'fixed';
|
|
437
|
+
textarea.style.opacity = '0';
|
|
438
|
+
document.body.appendChild(textarea);
|
|
439
|
+
textarea.select();
|
|
440
|
+
document.execCommand('copy');
|
|
441
|
+
document.body.removeChild(textarea);
|
|
23
442
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
btn.addEventListener('click', () => {
|
|
27
|
-
const cmd = btn.closest('.install-cmd');
|
|
28
|
-
const text = cmd ? cmd.querySelector('code').innerText.trim() : '';
|
|
29
|
-
navigator.clipboard.writeText(text).then(() => {
|
|
30
|
-
const originalHTML = btn.innerHTML;
|
|
31
|
-
btn.innerHTML = '<i class="fa-solid fa-check"></i> Copied';
|
|
443
|
+
var originalHTML = btn.innerHTML;
|
|
444
|
+
btn.innerHTML = '<i class="fas fa-check"></i> Copied';
|
|
32
445
|
btn.classList.add('copied');
|
|
33
|
-
|
|
446
|
+
|
|
447
|
+
setTimeout(function() {
|
|
34
448
|
btn.innerHTML = originalHTML;
|
|
35
449
|
btn.classList.remove('copied');
|
|
36
450
|
}, 2000);
|
|
37
451
|
});
|
|
38
452
|
});
|
|
39
|
-
}
|
|
453
|
+
}
|
|
40
454
|
}
|
|
41
455
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
456
|
+
function initFAQ() {
|
|
457
|
+
var items = document.querySelectorAll('.faq-item');
|
|
458
|
+
for (var i = 0; i < items.length; i++) {
|
|
459
|
+
items[i].addEventListener('toggle', function() {
|
|
460
|
+
if (this.open) {
|
|
461
|
+
for (var j = 0; j < items.length; j++) {
|
|
462
|
+
if (items[j] !== this && items[j].open) {
|
|
463
|
+
items[j].open = false;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
function initScrollSpy() {
|
|
472
|
+
var sections = document.querySelectorAll('section[id]');
|
|
473
|
+
if (sections.length === 0) return;
|
|
57
474
|
|
|
58
|
-
|
|
475
|
+
var navLinks = document.querySelectorAll('.nav-links a, .mobile-menu a');
|
|
59
476
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
477
|
+
var observer = new IntersectionObserver(function(entries) {
|
|
478
|
+
for (var i = 0; i < entries.length; i++) {
|
|
479
|
+
if (entries[i].isIntersecting) {
|
|
480
|
+
var id = entries[i].target.getAttribute('id');
|
|
481
|
+
|
|
482
|
+
for (var j = 0; j < navLinks.length; j++) {
|
|
483
|
+
var link = navLinks[j];
|
|
484
|
+
if (link.getAttribute('href') === '#' + id) {
|
|
485
|
+
link.classList.add('active');
|
|
486
|
+
link.style.color = '#10b981';
|
|
487
|
+
} else {
|
|
488
|
+
link.classList.remove('active');
|
|
489
|
+
link.style.color = '';
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}, {
|
|
495
|
+
rootMargin: '-20% 0px -70% 0px',
|
|
496
|
+
threshold: 0
|
|
63
497
|
});
|
|
64
498
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
499
|
+
for (var i = 0; i < sections.length; i++) {
|
|
500
|
+
observer.observe(sections[i]);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function initGSAPAnimations() {
|
|
505
|
+
if (typeof gsap === 'undefined') return;
|
|
506
|
+
|
|
507
|
+
gsap.registerPlugin(ScrollTrigger);
|
|
508
|
+
|
|
509
|
+
var prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
510
|
+
if (prefersReducedMotion) return;
|
|
511
|
+
|
|
512
|
+
var heroTimeline = gsap.timeline({ defaults: { ease: 'power3.out', duration: 0.8 } });
|
|
513
|
+
|
|
514
|
+
heroTimeline
|
|
515
|
+
.from('.hero-badge', { opacity: 0, y: 30, duration: 0.6 })
|
|
516
|
+
.from('.hero-title', { opacity: 0, y: 40, duration: 0.8 }, '-=0.4')
|
|
517
|
+
.from('.hero-subtitle', { opacity: 0, y: 30, duration: 0.6 }, '-=0.4')
|
|
518
|
+
.from('.hero-actions', { opacity: 0, y: 30, duration: 0.6 }, '-=0.3')
|
|
519
|
+
.from('.hero-code', { opacity: 0, y: 40, scale: 0.95, duration: 0.8 }, '-=0.3');
|
|
520
|
+
|
|
521
|
+
gsap.utils.toArray('.section-tag, .section-title, .section-lead').forEach(function(el, i) {
|
|
522
|
+
gsap.from(el, {
|
|
523
|
+
scrollTrigger: {
|
|
524
|
+
trigger: el,
|
|
525
|
+
start: 'top 85%',
|
|
526
|
+
end: 'top 60%',
|
|
527
|
+
toggleActions: 'play none none none'
|
|
528
|
+
},
|
|
529
|
+
opacity: 0,
|
|
530
|
+
y: 40,
|
|
531
|
+
duration: 0.7,
|
|
532
|
+
ease: 'power3.out'
|
|
533
|
+
});
|
|
68
534
|
});
|
|
69
535
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
536
|
+
gsap.utils.toArray('.feature-card').forEach(function(card, i) {
|
|
537
|
+
gsap.from(card, {
|
|
538
|
+
scrollTrigger: {
|
|
539
|
+
trigger: card,
|
|
540
|
+
start: 'top 85%',
|
|
541
|
+
toggleActions: 'play none none none'
|
|
542
|
+
},
|
|
543
|
+
opacity: 0,
|
|
544
|
+
y: 50,
|
|
545
|
+
duration: 0.7,
|
|
546
|
+
delay: i * 0.1,
|
|
547
|
+
ease: 'power3.out'
|
|
548
|
+
});
|
|
73
549
|
});
|
|
74
|
-
}
|
|
75
550
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
551
|
+
gsap.utils.toArray('.stat-item').forEach(function(item, i) {
|
|
552
|
+
gsap.from(item, {
|
|
553
|
+
scrollTrigger: {
|
|
554
|
+
trigger: item,
|
|
555
|
+
start: 'top 85%',
|
|
556
|
+
toggleActions: 'play none none none'
|
|
557
|
+
},
|
|
558
|
+
opacity: 0,
|
|
559
|
+
y: 30,
|
|
560
|
+
duration: 0.6,
|
|
561
|
+
delay: i * 0.15,
|
|
562
|
+
ease: 'power3.out'
|
|
563
|
+
});
|
|
564
|
+
});
|
|
87
565
|
|
|
88
|
-
|
|
566
|
+
gsap.utils.toArray('.code-window').forEach(function(win) {
|
|
567
|
+
gsap.from(win, {
|
|
568
|
+
scrollTrigger: {
|
|
569
|
+
trigger: win,
|
|
570
|
+
start: 'top 85%',
|
|
571
|
+
toggleActions: 'play none none none'
|
|
572
|
+
},
|
|
573
|
+
opacity: 0,
|
|
574
|
+
y: 40,
|
|
575
|
+
scale: 0.95,
|
|
576
|
+
duration: 0.8,
|
|
577
|
+
ease: 'power3.out'
|
|
89
578
|
});
|
|
90
579
|
});
|
|
91
|
-
}
|
|
92
580
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
a.style.color = active ? 'var(--text)' : '';
|
|
106
|
-
});
|
|
581
|
+
gsap.utils.toArray('.faq-item').forEach(function(item, i) {
|
|
582
|
+
gsap.from(item, {
|
|
583
|
+
scrollTrigger: {
|
|
584
|
+
trigger: item,
|
|
585
|
+
start: 'top 85%',
|
|
586
|
+
toggleActions: 'play none none none'
|
|
587
|
+
},
|
|
588
|
+
opacity: 0,
|
|
589
|
+
y: 30,
|
|
590
|
+
duration: 0.6,
|
|
591
|
+
delay: i * 0.1,
|
|
592
|
+
ease: 'power3.out'
|
|
107
593
|
});
|
|
108
|
-
}
|
|
594
|
+
});
|
|
109
595
|
|
|
110
|
-
|
|
596
|
+
gsap.utils.toArray('.cli-item').forEach(function(item, i) {
|
|
597
|
+
gsap.from(item, {
|
|
598
|
+
scrollTrigger: {
|
|
599
|
+
trigger: item,
|
|
600
|
+
start: 'top 85%',
|
|
601
|
+
toggleActions: 'play none none none'
|
|
602
|
+
},
|
|
603
|
+
opacity: 0,
|
|
604
|
+
x: -30,
|
|
605
|
+
duration: 0.6,
|
|
606
|
+
delay: i * 0.12,
|
|
607
|
+
ease: 'power3.out'
|
|
608
|
+
});
|
|
609
|
+
});
|
|
111
610
|
}
|
|
112
611
|
|
|
113
|
-
/* ── Scroll progress bar ─────────────────────────────────────────────────── */
|
|
114
612
|
function initScrollProgress() {
|
|
115
|
-
|
|
613
|
+
var bar = document.getElementById('scroll-progress');
|
|
116
614
|
if (!bar) {
|
|
117
615
|
bar = document.createElement('div');
|
|
118
616
|
bar.id = 'scroll-progress';
|
|
119
617
|
document.body.appendChild(bar);
|
|
120
618
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
619
|
+
|
|
620
|
+
bar.style.cssText = 'position:fixed;top:0;left:0;height:3px;width:0;z-index:9999;background:linear-gradient(90deg,#10b981,#059669);transition:width 0.1s linear;pointer-events:none;';
|
|
621
|
+
|
|
622
|
+
window.addEventListener('scroll', function() {
|
|
623
|
+
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
|
|
624
|
+
var docHeight = document.documentElement.scrollHeight - window.innerHeight;
|
|
625
|
+
var progress = docHeight > 0 ? (scrollTop / docHeight) * 100 : 0;
|
|
626
|
+
bar.style.width = progress + '%';
|
|
627
|
+
});
|
|
129
628
|
}
|
|
130
629
|
|
|
131
|
-
/* ── Back to top button ──────────────────────────────────────────────────── */
|
|
132
630
|
function initBackToTop() {
|
|
133
|
-
|
|
631
|
+
var btn = document.getElementById('to-top');
|
|
134
632
|
if (!btn) {
|
|
135
633
|
btn = document.createElement('button');
|
|
136
634
|
btn.id = 'to-top';
|
|
137
|
-
btn.
|
|
138
|
-
btn.setAttribute('aria-label', 'Back to top');
|
|
139
|
-
btn.innerHTML = '<i class="fa-solid fa-arrow-up"></i>';
|
|
635
|
+
btn.innerHTML = '<i class="fas fa-arrow-up"></i>';
|
|
140
636
|
document.body.appendChild(btn);
|
|
141
637
|
}
|
|
142
|
-
|
|
638
|
+
|
|
639
|
+
btn.style.cssText = 'position:fixed;bottom:30px;right:30px;width:48px;height:48px;border-radius:50%;background:#10b981;color:#fff;border:none;cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center;opacity:0;visibility:hidden;transform:translateY(20px);transition:all 0.3s ease;z-index:9998;box-shadow:0 4px 15px rgba(16,185,129,0.4);';
|
|
640
|
+
|
|
641
|
+
window.addEventListener('scroll', function() {
|
|
642
|
+
if (window.pageYOffset > 400) {
|
|
643
|
+
btn.style.opacity = '1';
|
|
644
|
+
btn.style.visibility = 'visible';
|
|
645
|
+
btn.style.transform = 'translateY(0)';
|
|
646
|
+
} else {
|
|
647
|
+
btn.style.opacity = '0';
|
|
648
|
+
btn.style.visibility = 'hidden';
|
|
649
|
+
btn.style.transform = 'translateY(20px)';
|
|
650
|
+
}
|
|
651
|
+
});
|
|
652
|
+
|
|
653
|
+
btn.addEventListener('click', function() {
|
|
143
654
|
window.scrollTo({ top: 0, behavior: 'smooth' });
|
|
144
655
|
});
|
|
145
|
-
const toggle = () => {
|
|
146
|
-
btn.classList.toggle('visible', window.scrollY > 480);
|
|
147
|
-
};
|
|
148
|
-
window.addEventListener('scroll', toggle, { passive: true });
|
|
149
|
-
toggle();
|
|
150
656
|
}
|
|
151
657
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
658
|
+
function initSmoothScroll() {
|
|
659
|
+
var links = document.querySelectorAll('a[href^="#"]');
|
|
660
|
+
for (var i = 0; i < links.length; i++) {
|
|
661
|
+
links[i].addEventListener('click', function(e) {
|
|
662
|
+
var href = this.getAttribute('href');
|
|
663
|
+
if (href === '#' || href === '#top') {
|
|
664
|
+
e.preventDefault();
|
|
665
|
+
window.scrollTo({ top: 0, behavior: 'smooth' });
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
161
668
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
observer.unobserve(entry.target);
|
|
669
|
+
var target = document.querySelector(href);
|
|
670
|
+
if (target) {
|
|
671
|
+
e.preventDefault();
|
|
672
|
+
target.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
|
167
673
|
}
|
|
168
674
|
});
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
targets.forEach(el => observer.observe(el));
|
|
675
|
+
}
|
|
172
676
|
}
|
|
173
677
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
678
|
+
var LIBRARY = [
|
|
679
|
+
{cat:"variables",name:"Declare Variable",desc:"Store a value in a named variable",ps:'remember name as "Ayokunle"\nremember age as 25\nremember pi as 3.14',js:'let name = "Ayokunle";\nlet age = 25;\nlet pi = 3.14;'},
|
|
680
|
+
{cat:"variables",name:"Reassign Variable",desc:"Change the value of an existing variable",ps:'remember count as 0\ncount becomes 10',js:'let count = 0;\ncount = 10;'},
|
|
681
|
+
{cat:"variables",name:"Type Coercion",desc:"Convert values between types",ps:'remember num as number("42")\nremember str as text(100)',js:'let num = Number("42");\nlet str = String(100);'},
|
|
682
|
+
{cat:"strings",name:"String Literals",desc:"Create string values with double quotes or backticks",ps:'remember greeting as "Hello, World!"\nremember name as "Ayokunle"',js:'let greeting = "Hello, World!";\nlet name = "Ayokunle";'},
|
|
683
|
+
{cat:"strings",name:"String Interpolation",desc:"Embed variables inside template literals",ps:'remember name as "Ayokunle"\nshow `Hello ${name}!`',js:'let name = "Ayokunle";\nconsole.log(`Hello ${name}!`);'},
|
|
684
|
+
{cat:"strings",name:"Uppercase / Lowercase",desc:"Change the case of a string",ps:'show uppercase("hello")\nshow lowercase("WORLD")',js:'console.log("hello".toUpperCase());\nconsole.log("WORLD".toLowerCase());'},
|
|
685
|
+
{cat:"strings",name:"String Length",desc:"Get the number of characters in a string",ps:'remember len as length("abc")\nshow len',js:'let len = "abc".length;\nconsole.log(len);'},
|
|
686
|
+
{cat:"strings",name:"Trim Whitespace",desc:"Remove leading and trailing whitespace",ps:'remember clean as trim(" hello ")',js:'let clean = " hello ".trim();'},
|
|
687
|
+
{cat:"strings",name:"Replace Text",desc:"Replace occurrences in a string",ps:'remember result as replace("hello world", "world", "JS")',js:'let result = "hello world".split("world").join("JS");'},
|
|
688
|
+
{cat:"strings",name:"Split String",desc:"Split a string into an array by delimiter",ps:'remember parts as split("a,b,c", ",")',js:'let parts = "a,b,c".split(",");'},
|
|
689
|
+
{cat:"strings",name:"Join Array",desc:"Join array elements into a string",ps:'remember text as join(["a","b","c"], ",")',js:'let text = ["a","b","c"].join(",");'},
|
|
690
|
+
{cat:"numbers",name:"Arithmetic",desc:"Basic math operations",ps:'remember a as 10 + 5\nremember b as 20 - 3\nremember c as 4 * 7\nremember d as 15 / 3\nremember e as 17 % 5',js:'let a = 10 + 5;\nlet b = 20 - 3;\nlet c = 4 * 7;\nlet d = 15 / 3;\nlet e = 17 % 5;'},
|
|
691
|
+
{cat:"numbers",name:"Rounding",desc:"Round, floor, or ceiling a number",ps:'show round(3.7)\nshow floor(3.7)\nshow ceiling(3.2)',js:'console.log(Math.round(3.7));\nconsole.log(Math.floor(3.7));\nconsole.log(Math.ceil(3.2));'},
|
|
692
|
+
{cat:"numbers",name:"Random Number",desc:"Generate a random number between 0 and 1",ps:'remember roll as random()',js:'let roll = Math.random();'},
|
|
693
|
+
{cat:"numbers",name:"Array Math",desc:"Sum, min, and max of arrays",ps:'remember nums as [1, 2, 3, 4, 5]\nshow sum(nums)\nshow smallest(nums)\nshow largest(nums)',js:'let nums = [1, 2, 3, 4, 5];\nconsole.log(nums.reduce((a, b) => a + b, 0));\nconsole.log(Math.min(...nums));\nconsole.log(Math.max(...nums));'},
|
|
694
|
+
{cat:"booleans",name:"Comparisons",desc:"Compare values with natural English operators",ps:'if 5 is 5\n show "equal"\ndone\n\nif 5 is not 3\n show "not equal"\ndone\n\nif 10 is greater than 5\n show "bigger"\ndone\n\nif 3 is less than 7\n show "smaller"\ndone',js:'if (5 === 5) {\n console.log("equal");\n}\n\nif (5 !== 3) {\n console.log("not equal");\n}\n\nif (10 > 5) {\n console.log("bigger");\n}\n\nif (3 < 7) {\n console.log("smaller");\n}'},
|
|
695
|
+
{cat:"booleans",name:"Range Checks",desc:"Check if a value is between, at least, or at most",ps:'remember age as 25\nif age between 18 and 65\n show "working age"\ndone\n\nif age is at least 18\n show "adult"\ndone',js:'let age = 25;\nif (age >= 18 && age <= 65) {\n console.log("working age");\n}\n\nif (age >= 18) {\n console.log("adult");\n}'},
|
|
696
|
+
{cat:"booleans",name:"String Checks",desc:"Check if a string contains, starts with, or ends with",ps:'remember msg as "Hello World"\nif msg contains "World"\n show "found"\ndone\n\nif msg starts with "Hello"\n show "greeting"\ndone\n\nif msg ends with "World"\n show "ending"\ndone',js:'let msg = "Hello World";\nif (msg.includes("World")) {\n console.log("found");\n}\n\nif (msg.startsWith("Hello")) {\n console.log("greeting");\n}\n\nif (msg.endsWith("World")) {\n console.log("ending");\n}'},
|
|
697
|
+
{cat:"booleans",name:"Empty Checks",desc:"Check if a value is empty or not empty",ps:'remember items as []\nif items is empty\n show "no items"\ndone\n\nif items is not empty\n show "has items"\ndone',js:'let items = [];\nif (items.length === 0) {\n console.log("no items");\n}\n\nif (items.length > 0) {\n console.log("has items");\n}'},
|
|
698
|
+
{cat:"booleans",name:"Logical Operators",desc:"Combine conditions with and, or, not",ps:'remember age as 25\nremember name as "Ayo"\n\nif age is 25 and name is "Ayo"\n show "match"\ndone\n\nif age is 10 or age is 25\n show "found"\ndone\n\nif age is not empty\n show "has value"\ndone',js:'let age = 25;\nlet name = "Ayo";\n\nif (age === 25 && name === "Ayo") {\n console.log("match");\n}\n\nif (age === 10 || age === 25) {\n console.log("found");\n}\n\nif (!(age.length === 0)) {\n console.log("has value");\n}'},
|
|
699
|
+
{cat:"conditionals",name:"If / Otherwise",desc:"Branch logic based on conditions",ps:'remember score as 85\n\nif score is greater than 80\n show "grade A"\notherwise if score is greater than 60\n show "grade B"\notherwise\n show "grade C"\ndone',js:'let score = 85;\n\nif (score > 80) {\n console.log("grade A");\n} else if (score > 60) {\n console.log("grade B");\n} else {\n console.log("grade C");\n}'},
|
|
700
|
+
{cat:"loops",name:"For Each Loop",desc:"Iterate over every item in a collection",ps:'remember fruits as ["apple", "banana", "cherry"]\n\nfor each fruit in fruits\n show fruit\ndone',js:'let fruits = ["apple", "banana", "cherry"];\n\nfor (const fruit of fruits) {\n console.log(fruit);\n}'},
|
|
701
|
+
{cat:"loops",name:"While Loop",desc:"Repeat while a condition is true",ps:'remember count as 0\n\nwhile count is less than 5\n show count\n count becomes count + 1\ndone',js:'let count = 0;\n\nwhile (count < 5) {\n console.log(count);\n count = count + 1;\n}'},
|
|
702
|
+
{cat:"functions",name:"Define Function",desc:"Create a reusable block of code",ps:'make greet(name)\n show `Hello ${name}!`\ndone\n\ngreet("Ayokunle")',js:'function greet(name) {\n console.log(`Hello ${name}!`);\n}\n\ngreet("Ayokunle");'},
|
|
703
|
+
{cat:"functions",name:"Return Value",desc:"Return a value from a function",ps:'make add(a, b)\n give a + b\ndone\n\nremember result as add(5, 7)\nshow result',js:'function add(a, b) {\n return a + b;\n}\n\nlet result = add(5, 7);\nconsole.log(result);'},
|
|
704
|
+
{cat:"arrays",name:"Array Literal",desc:"Create an array of values",ps:'remember colors as ["red", "green", "blue"]\nremember nums as [1, 2, 3, 4, 5]',js:'let colors = ["red", "green", "blue"];\nlet nums = [1, 2, 3, 4, 5];'},
|
|
705
|
+
{cat:"arrays",name:"Access Elements",desc:"Get items by index (one-based English syntax)",ps:'remember items as ["a", "b", "c"]\nshow first item from items\nshow last item from items\nshow items[0]',js:'let items = ["a", "b", "c"];\nconsole.log(items[0]);\nconsole.log(items[items.length - 1]);\nconsole.log(items[0]);'},
|
|
706
|
+
{cat:"arrays",name:"Add / Remove Items",desc:"Push to or splice from an array",ps:'remember list as [1, 2, 3]\nadd(4 to list)\nremove(2 from list)',js:'let list = [1, 2, 3];\nlist.push(4);\nlist.splice(list.indexOf(2), 1);'},
|
|
707
|
+
{cat:"arrays",name:"Sort / Reverse / Unique",desc:"Transform arrays with built-in operations",ps:'remember nums as [3, 1, 4, 1, 5]\nshow sort(nums)\nshow reverse(nums)\nshow unique(nums)',js:'let nums = [3, 1, 4, 1, 5];\nconsole.log([...nums].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)));\nconsole.log([...nums].reverse());\nconsole.log([...new Set(nums)]);'},
|
|
708
|
+
{cat:"objects",name:"Object Literal",desc:"Create an object with key-value pairs",ps:'remember user as\n name is "Ayokunle"\n age is 25\n role is "Developer"\ndone',js:'let user = {\n "name": "Ayokunle",\n "age": 25,\n "role": "Developer"\n};'},
|
|
709
|
+
{cat:"objects",name:"Access Properties",desc:"Read and write object properties",ps:'remember user as\n name is "Ayokunle"\n age is 25\ndone\n\nshow user.name\nshow name of user\nuser.age becomes 26',js:'let user = {\n "name": "Ayokunle",\n "age": 25\n};\n\nconsole.log(user.name);\nconsole.log(user.name);\nuser.age = 26;'},
|
|
710
|
+
{cat:"objects",name:"Object Utilities",desc:"Get keys, values, check properties, merge objects",ps:'remember user as\n name is "Ayo"\n age is 25\ndone\n\nshow keys(user)\nshow values(user)\nshow hasKey(user, "name")\n\nremember merged as merge(user, { city: "Lagos" })',js:'let user = {\n "name": "Ayo",\n "age": 25\n};\n\nconsole.log(Object.keys(user));\nconsole.log(Object.values(user));\nconsole.log(Object.prototype.hasOwnProperty.call(user, "name"));\n\nlet merged = { ...user, ...{ "city": "Lagos" } };'},
|
|
711
|
+
{cat:"imports",name:"Use npm Package",desc:"Import any npm package with the use keyword",ps:'use express\nuse axios\nuse dotenv\nuse chalk',js:'const express = require(\'express\');\nconst axios = require(\'axios\');\nrequire(\'dotenv\').config();\nconst chalk = require(\'chalk\');'},
|
|
712
|
+
{cat:"imports",name:"Use with Alias",desc:"Import a package under a different name",ps:'use node-fetch as fetch',js:'const fetch = require(\'node-fetch\');'},
|
|
713
|
+
{cat:"imports",name:"Import .ps File",desc:"Import another PlainScript file",ps:'import "./utils.ps"\nimport "./database.ps"',js:'// Bundled in dependency order at compile time'},
|
|
714
|
+
{cat:"server",name:"Web App",desc:"Create an Express server with one line",ps:'web app',js:'const express = require(\'express\');\nconst app = express();\napp.use(express.json());'},
|
|
715
|
+
{cat:"server",name:"Define Route",desc:"Handle HTTP requests with route blocks",ps:'web app\n\nroute "/"\n reply "Hello, World!"\ndone\n\nroute post "/users"\n reply json\n name is "Ayokunle"\n done\ndone',js:'const express = require(\'express\');\nconst app = express();\napp.use(express.json());\n\napp.get("/", (req, res) => {\n res.send("Hello, World!");\n});\n\napp.post("/users", (req, res) => {\n res.json({ "name": "Ayokunle" });\n});'},
|
|
716
|
+
{cat:"server",name:"Route Groups",desc:"Prefix multiple routes with a common path",ps:'group "/api"\n route "/users"\n reply "users list"\n done\n\n route "/posts"\n reply "posts list"\n done\ndone',js:'app.get("/api/users", (req, res) => {\n res.send("users list");\n});\n\napp.get("/api/posts", (req, res) => {\n res.send("posts list");\n});',skipRun:true},
|
|
717
|
+
{cat:"server",name:"Request Data",desc:"Access params, query, headers, and body",ps:'route "/users/:id"\n remember id as param("id")\n remember page as query("page")\n remember token as header("x-token")\n remember data as body of request\n show id\ndone',js:'app.get("/users/:id", (req, res) => {\n let id = req.params["id"];\n let page = req.query["page"];\n let token = req.headers["x-token"];\n let data = req.body;\n console.log(id);\n});',skipRun:true},
|
|
718
|
+
{cat:"server",name:"Static Files & CORS",desc:"Serve static files and enable CORS",ps:'web app\nserve folder "public"\nallow cors\nstart 3000',js:'const express = require(\'express\');\nconst app = express();\napp.use(express.json());\napp.use(express.static("public"));\n// CORS middleware added\napp.listen(3000);'},
|
|
719
|
+
{cat:"server",name:"Status Codes",desc:"Set HTTP response status codes",ps:'route "/not-found"\n status 404\n reply "Not found"\ndone',js:'app.get("/not-found", (req, res) => {\n res.status(404);\n res.send("Not found");\n});',skipRun:true},
|
|
720
|
+
{cat:"database",name:"Connect SQLite",desc:"Open a SQLite database connection",ps:'database "app.db"',js:'const db = await __dbOpen("app.db", null);'},
|
|
721
|
+
{cat:"database",name:"Query Data",desc:"Run a SELECT query and get results",ps:'remember rows as query\n SELECT * FROM users WHERE active = 1\ndone\n\nfor each row in rows\n show row.name\ndone',js:'let rows = db.prepare(\n "SELECT * FROM users WHERE active = 1"\n).all();\n\nfor (const row of rows) {\n console.log(row.name);\n}',skipRun:true},
|
|
722
|
+
{cat:"database",name:"Insert Data",desc:"Insert new rows into a table",ps:'insert\n INSERT INTO users (name, email)\n VALUES ("Ayokunle", "ayo@test.com")\ndone',js:'db.prepare(\n "INSERT INTO users (name, email) VALUES (?, ?)"\n).run("Ayokunle", "ayo@test.com");',skipRun:true},
|
|
723
|
+
{cat:"database",name:"Update Data",desc:"Update existing rows",ps:'update\n UPDATE users SET active = 0 WHERE id = 1\ndone',js:'db.prepare(\n "UPDATE users SET active = 0 WHERE id = 1"\n).run();',skipRun:true},
|
|
724
|
+
{cat:"database",name:"Create Tables",desc:"Execute DDL statements",ps:'execute\n CREATE TABLE IF NOT EXISTS users (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL,\n email TEXT UNIQUE\n )\ndone',js:'db.exec(\n "CREATE TABLE IF NOT EXISTS users (\\n id INTEGER PRIMARY KEY AUTOINCREMENT,\\n name TEXT NOT NULL,\\n email TEXT UNIQUE\\n )"\n);',skipRun:true},
|
|
725
|
+
{cat:"database",name:"Transactions",desc:"Wrap multiple operations in a transaction",ps:'transaction\n insert\n INSERT INTO accounts (name, balance) VALUES ("Ayo", 1000)\n done\n insert\n INSERT INTO accounts (name, balance) VALUES ("Dayo", 500)\n done\ndone',js:'db.transaction(() => {\n db.prepare("INSERT INTO accounts (name, balance) VALUES (?, ?)").run("Ayo", 1000);\n db.prepare("INSERT INTO accounts (name, balance) VALUES (?, ?)").run("Dayo", 500);\n})();',skipRun:true},
|
|
726
|
+
{cat:"database",name:"PostgreSQL",desc:"Connect to a PostgreSQL database",ps:'postgres env("DATABASE_URL")\n\nremember rows as query\n SELECT * FROM users LIMIT 10\ndone',js:'const pool = new Pool({ connectionString: process.env["DATABASE_URL"] });\nlet result = await pool.query("SELECT * FROM users LIMIT 10");\nlet rows = result.rows;'},
|
|
727
|
+
{cat:"cache",name:"Redis Cache",desc:"Connect to Redis for key-value caching",ps:'cache "redis://localhost:6379"',js:'// Creates Redis client and connects'},
|
|
728
|
+
{cat:"cache",name:"Get / Set Cache",desc:"Read and write cached values",ps:'cacheSet("user:1", "Ayokunle")\ncacheSet("token:abc", data, 3600)\n\nremember name as cacheGet("user:1")\nshow name',js:'await __cacheClient().set("user:1", "Ayokunle");\nawait __cacheClient().set("token:abc", data, { EX: 3600 });\n\nlet name = await __cacheClient().get("user:1");\nconsole.log(name);',skipRun:true},
|
|
729
|
+
{cat:"cache",name:"Delete Cache",desc:"Remove a cached key",ps:'cacheDelete("user:1")',js:'await __cacheClient().del("user:1");',skipRun:true},
|
|
730
|
+
{cat:"http",name:"GET Request",desc:"Fetch data from an API",ps:'remember response as get "https://api.example.com/users"\nshow data of response',js:'let response = await __httpRequest(\'GET\', "https://api.example.com/users", {});\nconsole.log(response.data);',skipRun:true},
|
|
731
|
+
{cat:"http",name:"POST Request",desc:"Send data to an API",ps:'remember body as\n name is "Ayokunle"\n email is "ayo@test.com"\ndone\n\nremember result as post "https://api.example.com/users" with body',js:'let body = {\n "name": "Ayokunle",\n "email": "ayo@test.com"\n};\n\nlet result = await __httpRequest(\'POST\', "https://api.example.com/users", { body });',skipRun:true},
|
|
732
|
+
{cat:"http",name:"PUT / PATCH / DELETE",desc:"Update or remove resources via API",ps:'put "https://api.example.com/users/1" with body\npatch "https://api.example.com/users/1" with body\ndelete "https://api.example.com/users/1"',js:'await __httpRequest(\'PUT\', url, { body });\nawait __httpRequest(\'PATCH\', url, { body });\nawait __httpRequest(\'DELETE\', "https://api.example.com/users/1", {});',skipRun:true},
|
|
733
|
+
{cat:"filesystem",name:"Read File",desc:"Read a file from disk",ps:'remember content as readFile("data.txt")\nshow content',js:'let content = fs.readFileSync("data.txt", \'utf8\');\nconsole.log(content);'},
|
|
734
|
+
{cat:"filesystem",name:"Write File",desc:"Write content to a file",ps:'writeFile("output.txt", "Hello World")\nwrite("data" to "output.txt")',js:'fs.writeFileSync("output.txt", "Hello World", \'utf8\');\nfs.writeFileSync("data", "output.txt", \'utf8\');'},
|
|
735
|
+
{cat:"filesystem",name:"File Operations",desc:"Check, copy, move, and delete files",ps:'show fileExists("data.txt")\ncopyFile("data.txt", "backup.txt")\nmoveFile("old.txt", "new.txt")\ndeleteFile("temp.txt")\nappendFile("log.txt", "new line\\n")',js:'console.log(fs.existsSync("data.txt"));\nfs.copyFileSync("data.txt", "backup.txt");\nfs.renameSync("old.txt", "new.txt");\nfs.unlinkSync("temp.txt");\nfs.appendFileSync("log.txt", "new line\\n", \'utf8\');'},
|
|
736
|
+
{cat:"filesystem",name:"Folder Operations",desc:"Create, list, and delete folders",ps:'makeFolder("src/components")\nshow listFolder("src")\ndeleteFolder("temp")',js:'fs.mkdirSync("src/components", { recursive: true });\nconsole.log(fs.readdirSync("src"));\nfs.rmSync("temp", { recursive: true, force: true });'},
|
|
737
|
+
{cat:"logging",name:"Show / Print",desc:"Output values to the console",ps:'show "Hello, World!"\nshow 42\nshow true\nprint("Debug info")',js:'console.log("Hello, World!");\nconsole.log(42);\nconsole.log(true);\nconsole.log("Debug info");'},
|
|
738
|
+
{cat:"datetime",name:"Timestamps",desc:"Get current time and create ISO dates",ps:'remember now as time()\nremember iso as date()\nshow now\nshow iso',js:'let now = Date.now();\nlet iso = new Date().toISOString();\nconsole.log(now);\nconsole.log(iso);'},
|
|
739
|
+
{cat:"datetime",name:"Sleep",desc:"Pause execution for a duration",ps:'show "waiting..."\nsleep(2000)\nshow "done"',js:'console.log("waiting...");\nAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 2000);\nconsole.log("done");'},
|
|
740
|
+
{cat:"datetime",name:"UUID & Environment",desc:"Generate UUIDs and read env vars",ps:'remember id as uuid()\nremember key as env("API_KEY")\nshow id\nshow key',js:'let id = crypto.randomUUID();\nlet key = process.env["API_KEY"];\nconsole.log(id);\nconsole.log(key);'},
|
|
741
|
+
{cat:"errors",name:"Try / Recover",desc:"Handle errors gracefully",ps:'try\n remember data as readFile("missing.txt")\nrecover as err\n show `Error: ${err}`\ndone',js:'try {\n let data = fs.readFileSync("missing.txt", \'utf8\');\n} catch (err) {\n console.log(`Error: ${err}`);\n}'},
|
|
742
|
+
{cat:"errors",name:"Retry",desc:"Automatically retry a failing operation",ps:'retry 3 times\n remember result as get "https://api.flaky.com/data"\ndone\n\nretry 5 times every 2 seconds\n remember result as get "https://api.flaky.com/data"\ndone',js:'for (let __attempt = 0; __attempt < 3; __attempt++) {\n try {\n let result = await __httpRequest(\'GET\', "https://api.flaky.com/data", {});\n break;\n } catch (__e) {}\n}'},
|
|
743
|
+
{cat:"async",name:"Wait For (Await)",desc:"Wait for an asynchronous operation to complete",ps:'remember data as wait for fetch("https://api.example.com/data")\nshow data',js:'let data = await fetch("https://api.example.com/data");\nconsole.log(data);'},
|
|
744
|
+
{cat:"async",name:"Run Background",desc:"Fire and forget an async operation",ps:'run background resizeImage("photo.png")\nrun background sendEmail(to, subject, body)',js:'setImmediate(() => { Promise.resolve(resizeImage("photo.png")).catch(() => {}); });\nsetImmediate(() => { Promise.resolve(sendEmail(to, subject, body)).catch(() => {}); });'},
|
|
745
|
+
{cat:"auth",name:"Password Hashing",desc:"Hash and verify passwords securely",ps:'remember hash as hashPassword("my-secret-pw")\nshow checkPassword("my-secret-pw", hash)',js:'let hash = hashPassword("my-secret-pw");\nconsole.log(checkPassword("my-secret-pw", hash));'},
|
|
746
|
+
{cat:"auth",name:"JWT Tokens",desc:"Create and verify JSON Web Tokens",ps:'remember token as createToken({ id: 1 }, "secret-key")\nshow readToken(token, "secret-key")',js:'let token = createToken({ "id": 1 }, "secret-key");\nconsole.log(readToken(token, "secret-key"));'},
|
|
747
|
+
{cat:"auth",name:"Sessions",desc:"Enable server-side sessions",ps:'web app\nenable sessions "my-secret-key"\n\nroute "/login"\n user of session of request becomes "Ayokunle"\n reply "Logged in"\ndone',js:'app.use(__enableSessions("my-secret-key"));\n\napp.get("/login", (req, res) => {\n __sessionOf(req).user = "Ayokunle";\n res.send("Logged in");\n});'},
|
|
748
|
+
{cat:"auth",name:"Cookies",desc:"Set, read, and clear cookies",ps:'route "/pref"\n set cookie "theme" to "dark"\n set cookie "lang" to "en" expires in 7 days\n remember theme as cookie("theme")\n clear cookie "theme"\ndone',js:'app.get("/pref", (req, res) => {\n res.cookie("theme", "dark", { httpOnly: true, path: \'/\' });\n res.cookie("lang", "en", { httpOnly: true, path: \'/\', maxAge: 604800000 });\n let theme = __cookieValue(req, "theme");\n res.clearCookie("theme", { path: \'/\' });\n});',skipRun:true},
|
|
749
|
+
{cat:"auth",name:"Rate Limiting",desc:"Protect endpoints from abuse",ps:'web app\nlimit requests to 100 per minute',js:'app.use(__rateLimit({ "max": 100, "windowMs": 60000 }));'},
|
|
750
|
+
{cat:"auth",name:"API Key Protection",desc:"Require an API key for access",ps:'web app\nrequire api key from env("API_KEY")',js:'// Middleware checks x-api-key header against process.env["API_KEY"]'},
|
|
751
|
+
{cat:"telegram",name:"Telegram Bot",desc:"Create a Telegram bot with command handlers",ps:'bot env("BOT_TOKEN")\n\nwhen someone sends "/start"\n reply "Welcome to PlainScript!"\ndone\n\nwhen someone sends matching "/echo (.+)"\n reply "echo"\ndone\n\nstart telegram bot',js:'BOT = await Telegram.createTelegramBot(process.env["BOT_TOKEN"]);\n\nBOT.onCommand("/start", async (ctx) => {\n await Telegram.sendMessage(ctx.chatId, "Welcome to PlainScript!");\n});\n\nBOT.onPattern(/echo (.+)/i, async (ctx) => {\n await Telegram.sendMessage(ctx.chatId, ctx.match[1]);\n});\n\nawait BOT.start();',skipRun:true},
|
|
752
|
+
{cat:"whatsapp",name:"WhatsApp Bot",desc:"Create a WhatsApp bot with message handlers",ps:'whatsapp bot\n on message\n reply "You said: ${message.text}"\n done\ndone',js:'await __whatsappStart({ "folder": "plainscript-whatsapp-auth", "login": "qr" });\n__whatsappOnMessage(async (__waCtx) => {\n await __whatsappReply(__waCtx.chat, `You said: ${__waCtx.message.text}`);\n});'},
|
|
753
|
+
{cat:"websocket",name:"WebSocket Server",desc:"Create a real-time WebSocket server",ps:'websocket server on 8080\n when socket connects\n send socket "Welcome!"\n done\n\n when socket sends message\n broadcast message\n done\n\ndone',js:'__wsServerCreate(8080, {\n connect: async (socket) => {\n __wsSend(socket, "Welcome!");\n },\n message: async (socket, message) => {\n __wsBroadcast(__wsServer, message);\n }\n});'},
|
|
754
|
+
{cat:"email",name:"Send Email",desc:"Configure SMTP and send emails",ps:'mail transport\n host is "smtp.gmail.com"\n port is 587\n user is env("EMAIL_USER")\n pass is env("EMAIL_PASS")\ndone\n\nsend mail\n from is "me@example.com"\n to is "friend@example.com"\n subject is "Hello"\n text is "PlainScript sends email!"\ndone',js:'__mailCreate({ "host": "smtp.gmail.com", "port": 587, "auth": { "user": process.env["EMAIL_USER"], "pass": process.env["EMAIL_PASS"] } });\n\nawait __mailSend({ "from": "me@example.com", "to": "friend@example.com", "subject": "Hello", "text": "PlainScript sends email!" });'},
|
|
755
|
+
{cat:"upload",name:"File Uploads",desc:"Accept and process file uploads",ps:'web app\naccept uploads limit "10 MB"\nallow ["image/png", "image/jpeg"]\nfolder "uploads"\n\nroute "/upload"\n remember file as upload("document")\n show file.name\n show file.size\ndone',js:'app.use(__uploads({ "limitBytes": 10485760, "mimes": ["image/png", "image/jpeg"], "folder": "uploads" }));\n\napp.get("/upload", (req, res) => {\n let file = __uploadedFile(req, "document");\n console.log(file.name);\n console.log(file.size);\n});'},
|
|
756
|
+
{cat:"cli",name:"CLI: new",desc:"Scaffold a new PlainScript project",ps:'plainscript new my-app',js:'// Creates my-app/ with src/app.ps and package.json',skipRun:true},
|
|
757
|
+
{cat:"cli",name:"CLI: run",desc:"Compile and execute a PlainScript file",ps:'plainscript run src/app.ps',js:'// Compiles src/app.ps and runs the output',skipRun:true},
|
|
758
|
+
{cat:"cli",name:"CLI: build",desc:"Compile .ps files to JavaScript",ps:'plainscript build',js:'// Compiles src/app.ps to dist/app.js',skipRun:true},
|
|
759
|
+
{cat:"cli",name:"CLI: fmt",desc:"Auto-format PlainScript code",ps:'plainscript fmt src/app.ps',js:'// Formats src/app.ps in place',skipRun:true},
|
|
760
|
+
{cat:"cli",name:"CLI: doctor",desc:"Diagnose project issues",ps:'plainscript doctor',js:'// Checks Node version, dependencies, config',skipRun:true},
|
|
761
|
+
{cat:"cli",name:"CLI: check",desc:"Type-check without emitting output",ps:'plainscript check src/app.ps',js:'// Validates syntax without compiling',skipRun:true},
|
|
762
|
+
{cat:"cli",name:"CLI: watch",desc:"Watch files and recompile on change",ps:'plainscript watch',js:'// Starts file watcher for .ps files',skipRun:true},
|
|
763
|
+
{cat:"cli",name:"CLI: install / add / remove",desc:"Manage project dependencies",ps:'plainscript install\nplainscript add express\nplainscript remove lodash',js:'// npm install / npm install express / npm uninstall lodash',skipRun:true},
|
|
764
|
+
{cat:"logging",name:"JavaScript Gateway",desc:"Embed raw JavaScript when you need full control",ps:'remember result as javascript\n return fetch("https://api.example.com/data")\n .then(r => r.json())\ndone\n\nshow result',js:'let result = await (async () => {\n return fetch("https://api.example.com/data")\n .then(r => r.json());\n})();\n\nconsole.log(result);'},
|
|
765
|
+
{cat:"booleans",name:"Ternary / Inline If",desc:"Use if expressions inline (via javascript gateway)",ps:'remember label as javascript\n return age >= 18 ? "adult" : "minor"\ndone',js:'let label = await (async () => {\n return age >= 18 ? "adult" : "minor";\n})();',skipRun:true},
|
|
766
|
+
{cat:"server",name:"404 Catch-All",desc:"Handle unmatched routes",ps:'when nothing matches\n status 404\n reply "Page not found"\ndone',js:'app.use((req, res) => {\n res.status(404);\n res.send("Page not found");\n});',skipRun:true},
|
|
767
|
+
{cat:"server",name:"Validate Request Body",desc:"Require specific fields in the request body",ps:'route post "/users"\n validate(body of request, ["name", "email"])\n reply "Created"\ndone',js:'app.post("/users", (req, res) => {\n __validate(req.body, ["name", "email"]);\n res.send("Created");\n});',skipRun:true},
|
|
768
|
+
{cat:"auth",name:"Google OAuth",desc:"Add Google login to your app",ps:'web app\ngoogle oauth\n id is env("GOOGLE_CLIENT_ID")\n secret is env("GOOGLE_CLIENT_SECRET")\n callback is "/auth/google/callback"\n landing is "/dashboard"\ndone',js:'__googleOAuth(app, {\n clientId: process.env["GOOGLE_CLIENT_ID"],\n clientSecret: process.env["GOOGLE_CLIENT_SECRET"],\n callbackUrl: "/auth/google/callback",\n afterLogin: "/dashboard"\n});'},
|
|
769
|
+
{cat:"cli",name:"CLI: version",desc:"Print the PlainScript version",ps:'plainscript version',js:'// Prints v1.0.0',skipRun:true},
|
|
770
|
+
{cat:"cli",name:"CLI: help",desc:"Show available commands",ps:'plainscript help',js:'// Lists all CLI commands',skipRun:true},
|
|
771
|
+
{cat:"cli",name:"CLI: info",desc:"Display platform and runtime info",ps:'plainscript info',js:'// Shows version, Node version, OS',skipRun:true},
|
|
772
|
+
{cat:"cli",name:"CLI: clean",desc:"Remove compiled output",ps:'plainscript clean',js:'// Deletes dist/ folder',skipRun:true},
|
|
773
|
+
{cat:"cli",name:"CLI: repl",desc:"Launch interactive REPL shell",ps:'plainscript repl',js:'// Opens interactive PlainScript REPL',skipRun:true},
|
|
774
|
+
{cat:"cli",name:"CLI: init",desc:"Initialize config file",ps:'plainscript init',js:'// Creates plainscript.config.json',skipRun:true},
|
|
775
|
+
{cat:"cli",name:"CLI: test",desc:"Run the test suite",ps:'plainscript test',js:'// Runs test files in tests/',skipRun:true},
|
|
776
|
+
{cat:"filesystem",name:"Binary File I/O",desc:"Read and write raw bytes",ps:'remember buf as readBytes("image.png")\nwriteBytes("copy.png", buf)',js:'let buf = fs.readFileSync("image.png");\nfs.writeFileSync("copy.png", buf);'},
|
|
777
|
+
{cat:"upload",name:"Multiple Uploads",desc:"Handle multiple file uploads at once",ps:'route "/upload-many"\n remember files as uploads("documents")\n for each f in files\n show f.name\n done\ndone',js:'app.get("/upload-many", (req, res) => {\n let files = __uploadedFiles(req, "documents");\n for (const f of files) {\n console.log(f.name);\n }\n});',skipRun:true},
|
|
778
|
+
{cat:"server",name:"Cron Jobs",desc:"Schedule recurring tasks",ps:'every 5 minutes\n show "running cleanup"\n // cleanup code here\ndone\n\nschedule "0 2 * * *"\n show "daily backup"\n // backup code here\ndone',js:'setInterval(async () => {\n console.log("running cleanup");\n}, 300000);\n\ncron.schedule("0 2 * * *", async () => {\n console.log("daily backup");\n});'},
|
|
779
|
+
{cat:"ai",name:"OCR (Optical Character Recognition)",desc:"Extract text from images using Tesseract OCR",ps:'ocr "screenshot.png" as extractedText\nshow extractedText\n\nocr "receipt.jpg" as receiptText using "eng+fra"',js:'let extractedText = await ocrImage("screenshot.png", "eng");\nconsole.log(extractedText);\n\nlet receiptText = await ocrImage("receipt.jpg", "eng+fra");'},
|
|
780
|
+
{cat:"data",name:"Gather (Map)",desc:"Transform every item in a collection",ps:'remember numbers as [1, 2, 3, 4, 5]\ngather each num in numbers giving num * 2\nshow numbers',js:'let numbers = [1, 2, 3, 4, 5];\nnumbers = numbers.map(num => num * 2);\nconsole.log(numbers);'},
|
|
781
|
+
{cat:"data",name:"Filter",desc:"Keep only items that match a condition",ps:'remember people as [{name: "Ayo", age: 25}, {name: "Tunde", age: 15}]\nfilter each person in people when person.age is above 17\nshow people',js:'let people = [{"name": "Ayo", "age": 25}, {"name": "Tunde", "age": 15}];\npeople = people.filter(person => person.age > 17);\nconsole.log(people);'},
|
|
782
|
+
{cat:"data",name:"Total (Reduce)",desc:"Combine all items into a single value",ps:'remember numbers as [1, 2, 3, 4, 5]\ntotal each num in numbers giving num\nshow numbers',js:'let numbers = [1, 2, 3, 4, 5];\nnumbers = numbers.reduce((__sum, num) => __sum + num, 0);\nconsole.log(numbers);'},
|
|
783
|
+
{cat:"data",name:"Pattern Matching",desc:"Match a value against multiple cases",ps:'remember command as "start"\nmatch command against\n "start" -> show "starting"\n "stop" -> show "stopping"\n otherwise -> show "unknown"\ndone',js:'let command = "start";\nswitch (command) {\n case "start":\n console.log("starting");\n break;\n case "stop":\n console.log("stopping");\n break;\n default:\n console.log("unknown");\n break;\n}'},
|
|
784
|
+
{cat:"data",name:"Regular Expressions",desc:"Match text patterns with regex",ps:'remember email as "ayo@test.com"\nmatch pattern "(\\w+)@(\\w+)" in email as parts\nshow parts',js:'let email = "ayo@test.com";\nlet parts = email.match(new RegExp("(\\\\w+)@(\\\\w+)"));\nconsole.log(parts);'},
|
|
785
|
+
{cat:"data",name:"Dynamic Property Access",desc:"Use a variable as an object key",ps:'remember key as "name"\nremember user as {name: "Ayo", age: 25}\nremember value as user[key]\nshow value',js:'let key = "name";\nlet user = { "name": "Ayo", "age": 25 };\nlet value = user[key];\nconsole.log(value);'},
|
|
786
|
+
{cat:"async",name:"Parallel Async",desc:"Run multiple async operations concurrently",ps:'make slowJob()\n sleep(10)\n give "slow"\ndone\nmake fastJob()\n sleep(5)\n give "fast"\ndone\nremember results as all of [slowJob(), fastJob()]\nshow results',js:'const results = await Promise.all([slowJob(), fastJob()]);\nconsole.log(results);'},
|
|
787
|
+
{cat:"async",name:"Event Emitter",desc:"Create decoupled publish/subscribe systems",ps:'emit "user.login" with user\n\nwhen "user.login" happens as data\n show `User logged in: ${data}`\ndone',js:'__emitter.emit("user.login", user);\n\n__emitter.on("user.login", (data) => {\n console.log(`User logged in: ${data}`);\n});',skipRun:true},
|
|
788
|
+
{cat:"async",name:"Stream Processing",desc:"Process large files line by line without loading into memory",ps:'stream "data.csv" as line\n show line\ndone',js:'await __streamFile("data.csv", async (line) => {\n console.log(line);\n});'},
|
|
789
|
+
{cat:"async",name:"Worker Threads",desc:"Run operations in parallel for faster execution",ps:'run in parallel\n remember a as wait for slowJob()\n remember b as wait for fastJob()\ndone as results',js:'const results = await Promise.all([(async () => {\n let a = (await slowJob());\n let b = (await fastJob());\n})()]);',skipRun:true},
|
|
790
|
+
{cat:"errors",name:"Typed Error Recovery",desc:"Catch specific error types separately",ps:'try\n riskyOperation()\nrecover when err catches "TypeError"\n show "type error"\nrecover when err catches "NetworkError"\n show "network error"\nrecover\n show "other error"\ndone',js:'try {\n riskyOperation();\n} catch (err) {\n if (err instanceof TypeError) {\n console.log("type error");\n }\n else if (err instanceof NetworkError) {\n console.log("network error");\n }\n else {\n console.log("other error");\n }\n}',skipRun:true},
|
|
791
|
+
{cat:"functions",name:"Default Parameters",desc:"Provide fallback values for function arguments",ps:'make greet(name, greeting as "Hello")\n show `${greeting}, ${name}!`\ndone\n\ngreet("Ayo")\ngreet("Ayo", "Hey")',js:'function greet(name, greeting = "Hello") {\n console.log(`${greeting}, ${name}!`);\n}\n\ngreet("Ayo");\ngreet("Ayo", "Hey");'},
|
|
792
|
+
{cat:"conditionals",name:"Else-If Chain",desc:"Test several conditions in order with otherwise if",ps:'remember score as 85\n\nif score is above 80\n show "grade A"\notherwise if score is above 60\n show "grade B"\notherwise\n show "grade C"\ndone',js:'let score = 85;\nif (score > 80) {\n console.log("grade A");\n} else if (score > 60) {\n console.log("grade B");\n} else {\n console.log("grade C");\n}'},
|
|
793
|
+
{cat:"conditionals",name:"Nested If",desc:"Nest an if inside another branch",ps:'remember a as 2\nif a is 1\n show "one"\notherwise\n if a is 2\n show "two"\n done\ndone',js:'let a = 2;\nif (a === 1) {\n console.log("one");\n} else {\n if (a === 2) console.log("two");\n}'},
|
|
794
|
+
{cat:"pattern",name:"Match Against Cases",desc:"Switch on a value against string, number, or boolean cases",ps:'remember color as "green"\n\nmatch color against\n "red" -> show "stop"\n "green" -> show "go"\n otherwise -> show "hold"\ndone',js:'let color = "green";\nswitch (color) {\n case "red": console.log("stop"); break;\n case "green": console.log("go"); break;\n default: console.log("hold");\n}'},
|
|
795
|
+
{cat:"pattern",name:"Match Numbers",desc:"Switch on numeric cases",ps:'remember n as 2\nmatch n against\n 1 -> show "one"\n 2 -> show "two"\n otherwise -> show "many"\ndone',js:'let n = 2;\nswitch (n) {\n case 1: console.log("one"); break;\n case 2: console.log("two"); break;\n default: console.log("many");\n}'},
|
|
796
|
+
{cat:"pattern",name:"Match Booleans",desc:"Switch on boolean cases",ps:'remember flag as true\nmatch flag against\n true -> show "switched on"\n false -> show "off"\ndone',js:'let flag = true;\nswitch (flag) {\n case true: console.log("switched on"); break;\n case false: console.log("off");\n}'},
|
|
797
|
+
{cat:"regex",name:"Regex Match",desc:"Capture regex groups from text",ps:'match pattern "(\\\\d+)-(\\\\d+)" in "order 12-34" as m\nshow m[1]\nshow m[2]',js:'const m = "order 12-34".match(new RegExp("(\\\\d+)-(\\\\d+)"));\nconsole.log(m[1]);\nconsole.log(m[2]);'},
|
|
798
|
+
{cat:"regex",name:"Regex Replace",desc:"Replace every regex match in a string",ps:'show regexReplace("a1b2c3", "\\\\d", "#")',js:'console.log("a1b2c3".replace(new RegExp("\\\\d", "g"), "#"));'},
|
|
799
|
+
{cat:"regex",name:"Regex Split",desc:"Split on a regex pattern",ps:'remember parts as split("a1b2", "\\\\d")\nshow parts',js:'let parts = "a1b2".split(/\\d/);\nconsole.log(parts);'},
|
|
800
|
+
{cat:"concurrency",name:"All Of (Promise.all)",desc:"Await every promise and collect results",ps:'make fetchA()\n give "a"\ndone\nmake fetchB()\n give "b"\ndone\nremember both as all of [fetchA(), fetchB()]\nshow both',js:'let both = await Promise.all([fetchA(), fetchB()]);\nconsole.log(both);'},
|
|
801
|
+
{cat:"concurrency",name:"Any Of (Promise.race)",desc:"Resolve with the first promise to settle",ps:'make slow()\n give "slow"\ndone\nmake fast()\n give "fast"\ndone\nremember winner as any of [slow(), fast()]\nshow winner',js:'let winner = await Promise.race([slow(), fast()]);\nconsole.log(winner);'},
|
|
802
|
+
{cat:"concurrency",name:"Settled Of (Promise.allSettled)",desc:"Await all promises; each yields status/value/reason",ps:'make ok(x)\n give x\ndone\nremember s as settled of [ok(1), ok(2)]\nshow s[0].status\nshow s[1].value',js:'let s = await Promise.allSettled([ok(1), ok(2)]);\nconsole.log(s[0].status);\nconsole.log(s[1].value);'},
|
|
803
|
+
{cat:"concurrency",name:"With Timeout",desc:"Reject a promise if it does not settle in time",ps:'make job()\n sleep(500)\n give "done"\ndone\nremember r as withTimeout(job(), 100)\nshow "finished"',js:'let r = await __withTimeout(job(), 100);\nconsole.log("finished");'},
|
|
804
|
+
{cat:"async",name:"Await (wait for)",desc:"Await a promise to get its resolved value",ps:'make fetchData()\n give 42\ndone\nremember value as wait for fetchData()\nshow value',js:'let value = (await fetchData());\nconsole.log(value);'},
|
|
805
|
+
{cat:"async",name:"Run in Parallel",desc:"Run blocks concurrently and collect results",ps:'run in parallel\n show "task1"\n show "task2"\ndone as results',js:'const results = await Promise.all([(async () => { console.log("task1"); console.log("task2"); })()]);'},
|
|
806
|
+
{cat:"async",name:"Stream File",desc:"Process a file line by line without loading it whole",ps:'stream "data.csv" as line\n show line\ndone',js:'await __streamFile("data.csv", async (line) => { console.log(line); });'},
|
|
807
|
+
{cat:"generators",name:"Yield Generator",desc:"yield inside make makes a generator",ps:'make countUp(n)\n remember i as 0\n while i is less than n\n i becomes i + 1\n yield i\n done\ndone\nshow spread of countUp(3)',js:'function* countUp(n) {\n let i = 0;\n while (i < n) { i = i + 1; yield i; }\n}\nconsole.log([...countUp(3)]);'},
|
|
808
|
+
{cat:"generators",name:"Spread Of",desc:"Materialize any iterable into a fresh array",ps:'show spread of "abc"\nshow spread of [1, 2, 3]',js:'console.log([..."abc"]);\nconsole.log([...[1, 2, 3]]);'},
|
|
809
|
+
{cat:"reflection",name:"Type Of",desc:"Classify a value by its PlainScript type",ps:'show typeOf("hi")\nshow typeOf(42)\nshow typeOf(true)\nshow typeOf([])\nshow typeOf({})\nshow typeOf(null)',js:'show typeOf -> text, number, boolean, array, record, null'},
|
|
810
|
+
{cat:"reflection",name:"Fields Of",desc:"List the keys of a record",ps:'remember u as {name: "A", age: 2}\nshow fieldsOf(u)',js:'show Object.keys(u)'},
|
|
811
|
+
{cat:"reflection",name:"Has Field",desc:"Check a record has a key without tripping on prototypes",ps:'remember u as {name: "A"}\nshow hasField(u, "name")\nshow hasField(u, "age")',js:'console.log(hasField(u, "name"));\nconsole.log(hasField(u, "age"));'},
|
|
812
|
+
{cat:"reflection",name:"Value Of",desc:"Read a field with a fallback if missing",ps:'remember u as {name: "A"}\nshow valueOf(u, "age", 0)',js:'show valueOf(u, "age", 0) // -> 0'},
|
|
813
|
+
{cat:"reflection",name:"Size Of",desc:"Length of a string/array, key count of a record",ps:'show sizeOf([1, 2, 3])\nshow sizeOf("abc")\nshow sizeOf({a: 1, b: 2})',js:'show 3, 3, 2'},
|
|
814
|
+
{cat:"binary",name:"Base64 Encode / Decode",desc:"Round-trip text with base64",ps:'show base64Encode("hello")\nshow base64Decode("aGVsbG8=")',js:'show Buffer "aGVsbG8="'},
|
|
815
|
+
{cat:"binary",name:"Bytes <-> Text",desc:"Convert text to a UTF-8 buffer and back",ps:'remember buf as textToBytes("hi")\nshow bytesToText(buf)',js:'show Buffer.from("hi","utf8") -> "hi"'},
|
|
816
|
+
{cat:"binary",name:"Hashing",desc:"Compute sha256 / sha1 / md5 hex digests",ps:'show sha256("abc")\nshow sha1("abc")\nshow md5("abc")',js:'show crypto digests (hex)'},
|
|
817
|
+
{cat:"binary",name:"Read / Write Bytes",desc:"Read and write raw binary files",ps:'writeBytes("out.bin", textToBytes("hi"))\nremember buf as readBytes("out.bin")\nshow bytesToText(buf)',js:'fs.writeFileSync("out.bin", Buffer.from("hi"));\nlet buf = fs.readFileSync("out.bin");\nconsole.log(buf.toString())'},
|
|
818
|
+
{cat:"booleans",name:"Null Coalesce",desc:"Pick the first value that is not null or undefined",ps:'remember config as {theme: null}\nremember theme as coalesce(theme of config, "light")\nshow theme',js:'let theme = (config.theme ?? "light");\nconsole.log(theme);'},
|
|
819
|
+
{cat:"datetime",name:"Parse Date",desc:"Turn a date string into milliseconds since the epoch",ps:'remember ms as parseDate("2020-01-02")\nshow ms',js:'show Date.parse("2020-01-02")'},
|
|
820
|
+
{cat:"datetime",name:"Format Date",desc:"Format milliseconds/Date with a pattern",ps:'remember ms as parseDate("2020-01-02")\nshow formatDate(ms, "DD/MM/YYYY")',js:'show formatDate -> "02/01/2020"'},
|
|
821
|
+
{cat:"config",name:"Load Env File",desc:"Apply KEY=VALUE pairs from a .env file",ps:'load env file ".env"\nshow env("PORT")',js:'__loadEnvFile(".env");\nconsole.log(process.env["PORT"]);'},
|
|
822
|
+
{cat:"config",name:"YAML Decode",desc:"Parse a YAML subset into a record",ps:'remember cfg as yamlDecode("name: Ada\\nport: 3000\\n")\nshow cfg.name',js:'show __yamlParse text -> record'},
|
|
823
|
+
{cat:"config",name:"YAML Encode",desc:"Serialize a record to YAML lines",ps:'remember text as yamlEncode({name: "Ada", port: 3000})\nshow text',js:'show __yamlStringify record -> text'},
|
|
824
|
+
{cat:"process",name:"Command-Line Args",desc:"Read command-line arguments after the script name",ps:'show args()',js:'show process.argv.slice(2)'},
|
|
825
|
+
{cat:"process",name:"Run Command",desc:"Run an external command and capture its output",ps:'remember r as runCommand("node", ["-e", "console.log(2+2)"])\nshow r.ok\nshow r.stdout',js:'let r = await __runCommand("node", ["-e", "console.log(2+2)"]);\nconsole.log(r.ok);\nconsole.log(r.stdout);'},
|
|
826
|
+
{cat:"process",name:"Load Module",desc:"Dynamically require a module at runtime",ps:'remember m as loadModule("./my-module")\nshow "loaded"',js:'let m = __loadModule("./my-module");\nconsole.log("loaded");'},
|
|
827
|
+
{cat:"filesystem",name:"File Metadata",desc:"Get size, type, and modified time of a file",ps:'show fileSize("data.txt")\nshow fileType("data.txt")\nshow lastModified("data.txt")',js:'show fs.statSync("data.txt").size / isDirectory / mtime'},
|
|
828
|
+
{cat:"filesystem",name:"Walk Folder",desc:"Recursively list every file path under a folder",ps:'for each f in walkFolder("src")\n show f\ndone',js:'for (const f of __walkFolder("src")) console.log(f);'},
|
|
829
|
+
{cat:"filesystem",name:"Append Line",desc:"Append a line terminated by a newline",ps:'writeLine("log.txt", "first")\nappendLine("log.txt", "second")',js:'fs.appendFileSync("log.txt", "first\\n", "utf8");\nfs.appendFileSync("log.txt", "second\\n", "utf8");'},
|
|
830
|
+
{cat:"paths",name:"Join Path",desc:"Join path segments for the current OS",ps:'show joinPath("a", "b", "c")',js:'show path.join("a", "b", "c")'},
|
|
831
|
+
{cat:"paths",name:"Base Name",desc:"Get the file name from a path",ps:'show baseName("/a/b.txt")',js:'show path.basename("/a/b.txt")'},
|
|
832
|
+
{cat:"paths",name:"Folder Of",desc:"Get the directory part of a path",ps:'show folderOf("/a/b.txt")',js:'show path.dirname("/a/b.txt")'},
|
|
833
|
+
{cat:"paths",name:"Extension Of",desc:"Get the extension of a path",ps:'show extensionOf("/a/b.txt")',js:'show path.extname("/a/b.txt")'},
|
|
834
|
+
{cat:"data",name:"Map Helpers",desc:"A keyed collection via keyMap and friends",ps:'remember m as keyMap()\nmapSet(m, "user", "Ada")\nshow mapGet(m, "user")\nshow mapHas(m, "user")\nmapDelete(m, "user")',js:'let m = new Map();\n__mapSet(m, "user", "Ada");\nconsole.log(m.get("user"));\nconsole.log(m.has("user"));\nm.delete("user");'},
|
|
835
|
+
{cat:"data",name:"Set Helpers",desc:"A de-duplicating collection via newSet and friends",ps:'remember s as newSet()\naddToSet(s, 1)\naddToSet(s, 1)\nshow setHas(s, 1) // true (dedup)',js:'let s = new Set();\ns.add(1);\ns.add(1);\nconsole.log(s.has(1));'},
|
|
836
|
+
{cat:"testing",name:"Native Test Suite",desc:"Declare a test block with check assertions",ps:'test "addition"\n check add(2, 3) equals 5\n check "hello" contains "ell"\n check 1 is 1\ndone\n\nmake add(a, b)\n give a + b\ndone',js:'const __tests = [];\n__tests.push(() => __check("equals", add(2,3), 5));\n__tests.push(() => __check("contains", "hello", "ell"));\n__tests.push(() => __check("is", 1, 1));\n__runTests();'},
|
|
837
|
+
{cat:"testing",name:"Check Raises",desc:"Assert that an expression throws",ps:'test "invalid json"\n check jsonDecode("not json") raises "JSON"\ndone',js:'__check("raises", () => JSON.parse("not json"), "JSON");'},
|
|
838
|
+
{cat:"imports",name:"Export Symbol",desc:"Mark a top-level symbol for module.exports",ps:'remember version as 3\nexport version',js:'module.exports.version = 3;'},
|
|
839
|
+
{cat:"ai",name:"OCR Image",desc:"Extract text from an image with tesseract.js",ps:'ocr "scan.png" as text\nshow text',js:'let text = await __ocr("scan.png", "eng");\nconsole.log(text);'},
|
|
840
|
+
{cat:"ai",name:"OCR Language",desc:"Choose a language pack for OCR",ps:'ocr "scan.png" as text using "deu"\nshow text',js:'let text = await __ocr("scan.png", "deu");\nconsole.log(text);'},
|
|
841
|
+
{cat:"logging",name:"Ask Input",desc:"Prompt for a line of terminal input",ps:'ask "Your name?" as name\nshow `Hello, ${name}`',js:'let name = await __ask("Your name?");\nconsole.log(`Hello, ${name}`);'},
|
|
842
|
+
{cat:"data",name:"Gather (Map)",desc:"Transform every item in a collection",ps:'remember nums as [1, 2, 3]\ngather each n in nums giving n * 2\nshow nums',js:'nums = nums.map(n => n * 2);\nconsole.log(nums);'},
|
|
843
|
+
{cat:"data",name:"Filter Items",desc:"Keep only items that match a condition",ps:'remember nums as [1, 2, 3, 4]\nfilter each n in nums when n is above 2\nshow nums',js:'nums = nums.filter(n => n > 2);\nconsole.log(nums);'},
|
|
844
|
+
{cat:"data",name:"Total (Reduce)",desc:"Combine all items into one value",ps:'remember nums as [1, 2, 3]\ntotal each n in nums giving n\nshow nums',js:'nums = nums.reduce((sum, n) => sum + n, 0);\nconsole.log(nums);'},
|
|
845
|
+
{cat:"errors",name:"Try / Recover",desc:"Catch errors raised inside a block",ps:'try\n jsonDecode("not json")\nrecover as err\n show "caught"\ndone',js:'try {\n JSON.parse("not json");\n} catch (err) {\n console.log("caught");\n}'},
|
|
846
|
+
{cat:"errors",name:"Recover by Type",desc:"Catch specific error types with catches",ps:'try\n jsonDecode("x")\nrecover when err catches "SyntaxError"\n show "bad json"\nrecover\n show "other"\ndone',js:'try {\n JSON.parse("x");\n} catch (err) {\n if (err instanceof SyntaxError) console.log("bad json");\n else console.log("other");\n}'},
|
|
847
|
+
{cat:"errors",name:"Retry",desc:"Retry a block a number of times",ps:'retry 3 times\n show "attempt"\ndone',js:'for (let __i = 0; __i < 3; __i++) {\n console.log("attempt");\n}'},
|
|
848
|
+
{cat:"errors",name:"Retry with Delay",desc:"Retry with a delay between attempts",ps:'retry 3 times every 2 seconds\n show "retrying"\ndone',js:'for (let __i = 0; __i < 3; __i++) {\n console.log("retrying");\n if (__i < 2) await __retrySleep(2000);\n}'},
|
|
849
|
+
{cat:"errors",name:"Event Emitter",desc:"Publish and subscribe to named events",ps:'emit "user.login" with "Ada"\nwhen "user.login" happens as user\n show `welcome ${user}`\ndone',js:'__emitter.emit("user.login", "Ada");\n__emitter.on("user.login", (user) => { console.log(`welcome ${user}`); });'},
|
|
850
|
+
{cat:"http",name:"HTTP Headers & Timeout",desc:"Send HTTP requests with custom headers and timeout",ps:'remember r as get "https://api.example.com" headers { "x-key": "abc" } timeout 5000\nshow r.status',js:'let r = await __httpRequest("GET", url, { headers: {...}, timeoutMs: 5000 });\nconsole.log(r.status);',skipRun:true},
|
|
851
|
+
{cat:"server",name:"Typed Server Routes",desc:"Start a web app with typed route accessors",ps:'web app\nroute get "/u/:id"\n remember who as param("id")\n remember page as query("page")\n reply `user=${who} page=${page}`\ndone\nroute post "/check"\n remember missing as validate(body of request, ["name"])\n reply missing\ndone\nstart 3000',js:'const app = express();\napp.get("/u/:id", (req, res) => {\n const who = req.params["id"];\n const page = req.query["page"];\n res.send(`user=${who} page=${page}`);\n});\napp.post("/check", (req, res) => {\n res.send(__validate(req.body, ["name"]));\n});\napp.listen(3000);'},
|
|
852
|
+
{cat:"auth",name:"Password Hashing",desc:"Hash and verify passwords (scrypt)",ps:'remember hash as hashPassword("secret123")\nshow checkPassword("secret123", hash)',js:'let hash = hashPassword("secret123");\nconsole.log(checkPassword("secret123", hash));'},
|
|
853
|
+
{cat:"auth",name:"Signed Tokens",desc:"Create and verify HS256 JWTs",ps:'remember token as createToken({ role: "admin" }, "secret", 3600)\nremember claims as readToken(token, "secret")\nshow claims.role',js:'let token = createToken({ role: "admin" }, "secret", 3600);\nlet claims = readToken(token, "secret");\nconsole.log(claims.role);'},
|
|
854
|
+
];
|
|
855
|
+
|
|
856
|
+
function initLibrary() {
|
|
857
|
+
var grid = document.getElementById('lib-grid');
|
|
858
|
+
var searchInput = document.getElementById('lib-search');
|
|
859
|
+
var countEl = document.getElementById('lib-count');
|
|
860
|
+
var emptyEl = document.getElementById('lib-empty');
|
|
861
|
+
var filterBtns = document.querySelectorAll('.lib-filter');
|
|
862
|
+
if (!grid || !searchInput) return;
|
|
863
|
+
|
|
864
|
+
var activeCat = 'all';
|
|
865
|
+
|
|
866
|
+
function renderCards(features) {
|
|
867
|
+
grid.innerHTML = '';
|
|
868
|
+
if (features.length === 0) {
|
|
869
|
+
emptyEl.style.display = 'block';
|
|
870
|
+
countEl.textContent = '0 results';
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
emptyEl.style.display = 'none';
|
|
874
|
+
countEl.textContent = features.length + ' feature' + (features.length !== 1 ? 's' : '');
|
|
875
|
+
|
|
876
|
+
for (var i = 0; i < features.length; i++) {
|
|
877
|
+
var f = features[i];
|
|
878
|
+
var card = document.createElement('div');
|
|
879
|
+
card.className = 'lib-card';
|
|
880
|
+
card.setAttribute('data-cat', f.cat);
|
|
881
|
+
|
|
882
|
+
var header = '<div class="lib-card-header"><span class="lib-card-title">' + f.name + '</span><span class="lib-card-cat">' + f.cat + '</span></div>';
|
|
883
|
+
var body = '<div class="lib-card-body"><pre><code>' + escapeHtml(f.ps) + '</code></pre></div>';
|
|
884
|
+
var footer = '<div class="lib-card-footer"><div class="lib-card-js"><span>JS:</span> ' + escapeHtml(f.desc) + '</div></div>';
|
|
885
|
+
card.innerHTML = header + body + footer;
|
|
886
|
+
grid.appendChild(card);
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
if (typeof initSyntaxHighlighting === 'function') {
|
|
890
|
+
var codeEls = grid.querySelectorAll('code');
|
|
891
|
+
for (var j = 0; j < codeEls.length; j++) {
|
|
892
|
+
var text = codeEls[j].textContent;
|
|
893
|
+
codeEls[j].innerHTML = tokenize(text, 'plainscript');
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
function escapeHtml(str) {
|
|
899
|
+
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
function filterFeatures() {
|
|
903
|
+
var query = searchInput.value.toLowerCase().trim();
|
|
904
|
+
var results = [];
|
|
905
|
+
|
|
906
|
+
for (var i = 0; i < LIBRARY.length; i++) {
|
|
907
|
+
var f = LIBRARY[i];
|
|
908
|
+
var catMatch = activeCat === 'all' || f.cat === activeCat;
|
|
909
|
+
if (!catMatch) continue;
|
|
910
|
+
|
|
911
|
+
if (!query) {
|
|
912
|
+
results.push(f);
|
|
913
|
+
continue;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
var searchable = (f.name + ' ' + f.desc + ' ' + f.cat + ' ' + f.ps).toLowerCase();
|
|
917
|
+
if (searchable.indexOf(query) !== -1) {
|
|
918
|
+
results.push(f);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
renderCards(results);
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
searchInput.addEventListener('input', filterFeatures);
|
|
926
|
+
|
|
927
|
+
for (var i = 0; i < filterBtns.length; i++) {
|
|
928
|
+
filterBtns[i].addEventListener('click', function() {
|
|
929
|
+
for (var j = 0; j < filterBtns.length; j++) {
|
|
930
|
+
filterBtns[j].classList.remove('active');
|
|
182
931
|
}
|
|
932
|
+
this.classList.add('active');
|
|
933
|
+
activeCat = this.getAttribute('data-cat');
|
|
934
|
+
filterFeatures();
|
|
183
935
|
});
|
|
184
|
-
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
renderCards(LIBRARY);
|
|
185
939
|
}
|
|
186
940
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
941
|
+
document.addEventListener('DOMContentLoaded', function() {
|
|
942
|
+
initSyntaxHighlighting();
|
|
943
|
+
initThreeBackground();
|
|
190
944
|
initMobileMenu();
|
|
945
|
+
initCopyButtons();
|
|
191
946
|
initFAQ();
|
|
192
947
|
initScrollSpy();
|
|
193
|
-
|
|
948
|
+
initSmoothScroll();
|
|
194
949
|
initScrollProgress();
|
|
195
950
|
initBackToTop();
|
|
196
|
-
|
|
951
|
+
initGSAPAnimations();
|
|
952
|
+
initLibrary();
|
|
197
953
|
});
|