elegance-js 2.0.19 → 2.1.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.
@@ -1,591 +0,0 @@
1
- // src/dynamic_page.ts
2
- import fs from "fs";
3
- import path from "path";
4
- import esbuild from "esbuild";
5
- import { fileURLToPath } from "url";
6
-
7
- // src/shared/serverElements.ts
8
- var createBuildableElement = (tag) => {
9
- return (options, ...children) => ({
10
- tag,
11
- options: options || {},
12
- children
13
- });
14
- };
15
- var createChildrenlessBuildableElement = (tag) => {
16
- return (options) => ({
17
- tag,
18
- options: options || {},
19
- children: null
20
- });
21
- };
22
- var childrenlessElementTags = [
23
- "area",
24
- "base",
25
- "br",
26
- "col",
27
- "embed",
28
- "hr",
29
- "img",
30
- "input",
31
- "link",
32
- "meta",
33
- "source",
34
- "track",
35
- "path",
36
- "rect"
37
- ];
38
- var elementTags = [
39
- "a",
40
- "address",
41
- "article",
42
- "aside",
43
- "audio",
44
- "blockquote",
45
- "body",
46
- "button",
47
- "canvas",
48
- "caption",
49
- "colgroup",
50
- "data",
51
- "datalist",
52
- "dd",
53
- "del",
54
- "details",
55
- "dialog",
56
- "div",
57
- "dl",
58
- "dt",
59
- "fieldset",
60
- "figcaption",
61
- "figure",
62
- "footer",
63
- "form",
64
- "h1",
65
- "h2",
66
- "h3",
67
- "h4",
68
- "h5",
69
- "h6",
70
- "head",
71
- "header",
72
- "hgroup",
73
- "html",
74
- "iframe",
75
- "ins",
76
- "label",
77
- "legend",
78
- "li",
79
- "main",
80
- "map",
81
- "meter",
82
- "nav",
83
- "noscript",
84
- "object",
85
- "ol",
86
- "optgroup",
87
- "option",
88
- "output",
89
- "p",
90
- "picture",
91
- "pre",
92
- "progress",
93
- "q",
94
- "section",
95
- "select",
96
- "summary",
97
- "table",
98
- "tbody",
99
- "td",
100
- "template",
101
- "textarea",
102
- "tfoot",
103
- "th",
104
- "thead",
105
- "time",
106
- "tr",
107
- "ul",
108
- "video",
109
- "span",
110
- "script",
111
- "abbr",
112
- "b",
113
- "bdi",
114
- "bdo",
115
- "cite",
116
- "code",
117
- "dfn",
118
- "em",
119
- "i",
120
- "kbd",
121
- "mark",
122
- "rp",
123
- "rt",
124
- "ruby",
125
- "s",
126
- "samp",
127
- "small",
128
- "strong",
129
- "sub",
130
- "sup",
131
- "u",
132
- "wbr",
133
- "title",
134
- "svg"
135
- ];
136
- var elements = {};
137
- var childrenlessElements = {};
138
- for (const element of elementTags) {
139
- elements[element] = createBuildableElement(element);
140
- }
141
- for (const element of childrenlessElementTags) {
142
- childrenlessElements[element] = createChildrenlessBuildableElement(element);
143
- }
144
- var allElements = {
145
- ...elements,
146
- ...childrenlessElements
147
- };
148
-
149
- // src/shared/bindServerElements.ts
150
- Object.assign(globalThis, elements);
151
- Object.assign(globalThis, childrenlessElements);
152
-
153
- // src/server/render.ts
154
- var renderRecursively = (element) => {
155
- let returnString = "";
156
- if (typeof element === "boolean") return returnString;
157
- else if (typeof element === "number" || typeof element === "string") {
158
- return returnString + element;
159
- } else if (Array.isArray(element)) {
160
- return returnString + element.join(", ");
161
- }
162
- returnString += `<${element.tag}`;
163
- if (typeof element.options === "object") {
164
- const {
165
- tag: elementTag,
166
- options: elementOptions,
167
- children: elementChildren
168
- } = element.options;
169
- if (elementTag !== void 0 && elementOptions !== void 0 && elementChildren !== void 0) {
170
- const children = element.children;
171
- element.children = [
172
- element.options,
173
- ...children
174
- ];
175
- element.options = {};
176
- } else {
177
- for (const [attrName, attrValue] of Object.entries(element.options)) {
178
- if (typeof attrValue === "object") {
179
- throw `Attr ${attrName}, for element ${element.tag} has obj type. Got: ${JSON.stringify(element, null, 2)}`;
180
- }
181
- returnString += ` ${attrName.toLowerCase()}="${attrValue}"`;
182
- }
183
- }
184
- } else if (typeof element.options !== "object" && element.options !== void 0) {
185
- element.children = [element.options, ...element.children || []];
186
- }
187
- if (element.children === null) {
188
- returnString += "/>";
189
- return returnString;
190
- }
191
- returnString += ">";
192
- for (const child of element.children) {
193
- returnString += renderRecursively(child);
194
- }
195
- returnString += `</${element.tag}>`;
196
- return returnString;
197
- };
198
- var serverSideRenderPage = async (page, pathname) => {
199
- if (!page) {
200
- throw `No Page Provided.`;
201
- }
202
- if (typeof page === "function") {
203
- throw `Unbuilt page provided to ssr page.`;
204
- }
205
- const bodyHTML = renderRecursively(page);
206
- return {
207
- bodyHTML
208
- };
209
- };
210
-
211
- // src/server/generateHTMLTemplate.ts
212
- var generateHTMLTemplate = async ({
213
- pageURL,
214
- head: head2,
215
- serverData = null,
216
- addPageScriptTag = true,
217
- name,
218
- requiredClientModules = [],
219
- environment
220
- }) => {
221
- let StartTemplate = `<meta name="viewport" content="width=device-width, initial-scale=1.0">`;
222
- if (environment === "production") {
223
- StartTemplate += `<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">`;
224
- }
225
- StartTemplate += '<meta charset="UTF-8">';
226
- for (const module of requiredClientModules) {
227
- StartTemplate += `<script data-module="true" src="/shipped/${module}.js" defer="true"></script>`;
228
- }
229
- if (addPageScriptTag === true) {
230
- StartTemplate += `<script data-page="true" type="module" src="${pageURL === "" ? "" : "/"}${pageURL}/${name}_data.js" defer="true"></script>`;
231
- }
232
- StartTemplate += `<script type="module" src="/client.js" defer="true"></script>`;
233
- let builtHead;
234
- if (head2.constructor.name === "AsyncFunction") {
235
- builtHead = await head2();
236
- } else {
237
- builtHead = head2();
238
- }
239
- let HTMLTemplate = renderRecursively(builtHead);
240
- if (serverData) {
241
- HTMLTemplate += serverData;
242
- }
243
- return {
244
- internals: StartTemplate,
245
- builtMetadata: HTMLTemplate
246
- };
247
- };
248
-
249
- // src/server/createState.ts
250
- if (!globalThis.__SERVER_CURRENT_STATE_ID__) {
251
- globalThis.__SERVER_CURRENT_STATE_ID__ = 1;
252
- }
253
- var initializeState = () => {
254
- globalThis.__SERVER_CURRENT_STATE__ = [];
255
- };
256
- var getState = () => {
257
- return globalThis.__SERVER_CURRENT_STATE__;
258
- };
259
- var initializeObjectAttributes = () => globalThis.__SERVER_CURRENT_OBJECT_ATTRIBUTES__ = [];
260
- var getObjectAttributes = () => {
261
- return globalThis.__SERVER_CURRENT_OBJECT_ATTRIBUTES__;
262
- };
263
-
264
- // src/server/loadHook.ts
265
- var resetLoadHooks = () => globalThis.__SERVER_CURRENT_LOADHOOKS__ = [];
266
- var getLoadHooks = () => globalThis.__SERVER_CURRENT_LOADHOOKS__;
267
-
268
- // src/dynamic_page.ts
269
- var packageDir = process.env.PACKAGE_PATH;
270
- if (packageDir === void 0) {
271
- const __filename = fileURLToPath(import.meta.url);
272
- const __dirname = path.dirname(__filename);
273
- packageDir = path.resolve(__dirname, "..");
274
- }
275
- var elementKey = 0;
276
- var processOptionAsObjectAttribute = (element, optionName, optionValue, objectAttributes) => {
277
- const lcOptionName = optionName.toLowerCase();
278
- const options = element.options;
279
- let key = options.key;
280
- if (key == void 0) {
281
- key = elementKey += 1;
282
- options.key = key;
283
- }
284
- if (!optionValue.type) {
285
- throw `ObjectAttributeType is missing from object attribute. ${element.tag}: ${optionName}/${optionValue}`;
286
- }
287
- let optionFinal = lcOptionName;
288
- switch (optionValue.type) {
289
- case 1 /* STATE */:
290
- const SOA = optionValue;
291
- if (typeof SOA.value === "function") {
292
- delete options[optionName];
293
- break;
294
- }
295
- if (lcOptionName === "innertext" || lcOptionName === "innerhtml") {
296
- element.children = [SOA.value];
297
- delete options[optionName];
298
- } else {
299
- delete options[optionName];
300
- options[lcOptionName] = SOA.value;
301
- }
302
- break;
303
- case 2 /* OBSERVER */:
304
- const OOA = optionValue;
305
- const firstValue = OOA.update(...OOA.initialValues);
306
- if (lcOptionName === "innertext" || lcOptionName === "innerhtml") {
307
- element.children = [firstValue];
308
- delete options[optionName];
309
- } else {
310
- delete options[optionName];
311
- options[lcOptionName] = firstValue;
312
- }
313
- optionFinal = optionName;
314
- break;
315
- case 4 /* REFERENCE */:
316
- options["ref"] = optionValue.value;
317
- break;
318
- }
319
- objectAttributes.push({ ...optionValue, key, attribute: optionFinal });
320
- };
321
- var processPageElements = async (element, objectAttributes, parent) => {
322
- if (typeof element === "boolean" || typeof element === "number" || Array.isArray(element)) return element;
323
- if (typeof element === "string") {
324
- return element;
325
- }
326
- const processElementOptionsAsChildAndReturn = async () => {
327
- const children = element.children;
328
- element.children = [
329
- element.options,
330
- ...children
331
- ];
332
- element.options = {};
333
- for (let i = 0; i < children.length + 1; i++) {
334
- const child = element.children[i];
335
- const processedChild = await processPageElements(child, objectAttributes, element);
336
- element.children[i] = processedChild;
337
- }
338
- return {
339
- ...element,
340
- options: {}
341
- };
342
- };
343
- if (typeof element.options !== "object") {
344
- return await processElementOptionsAsChildAndReturn();
345
- }
346
- const {
347
- tag: elementTag,
348
- options: elementOptions,
349
- children: elementChildren
350
- } = element.options;
351
- if (elementTag && elementOptions && elementChildren) {
352
- return await processElementOptionsAsChildAndReturn();
353
- }
354
- const options = element.options;
355
- for (const [optionName, optionValue] of Object.entries(options)) {
356
- const lcOptionName = optionName.toLowerCase();
357
- if (typeof optionValue !== "object") {
358
- if (lcOptionName === "innertext") {
359
- delete options[optionName];
360
- if (element.children === null) {
361
- throw `Cannot use innerText or innerHTML on childrenless elements.`;
362
- }
363
- element.children = [optionValue, ...element.children];
364
- continue;
365
- } else if (lcOptionName === "innerhtml") {
366
- if (element.children === null) {
367
- throw `Cannot use innerText or innerHTML on childrenless elements.`;
368
- }
369
- delete options[optionName];
370
- element.children = [optionValue];
371
- continue;
372
- }
373
- continue;
374
- }
375
- ;
376
- processOptionAsObjectAttribute(element, optionName, optionValue, objectAttributes);
377
- }
378
- if (element.children) {
379
- for (let i = 0; i < element.children.length; i++) {
380
- const child = element.children[i];
381
- const processedChild = await processPageElements(child, objectAttributes, element);
382
- element.children[i] = processedChild;
383
- }
384
- }
385
- return element;
386
- };
387
- var generateSuitablePageElements = async (pageLocation, pageElements, metadata, DIST_DIR, pageName, requiredClientModules) => {
388
- if (typeof pageElements === "string" || typeof pageElements === "boolean" || typeof pageElements === "number" || Array.isArray(pageElements)) {
389
- return [];
390
- }
391
- const objectAttributes = [];
392
- const processedPageElements = await processPageElements(pageElements, objectAttributes, []);
393
- elementKey = 0;
394
- const renderedPage = await serverSideRenderPage(
395
- processedPageElements,
396
- pageLocation
397
- );
398
- const template = await generateHTMLTemplate({
399
- pageURL: path.relative(DIST_DIR, pageLocation),
400
- head: metadata,
401
- addPageScriptTag: true,
402
- name: pageName,
403
- requiredClientModules,
404
- environment: "production"
405
- });
406
- const resultHTML = `<!DOCTYPE html>${template}${renderedPage.bodyHTML}`;
407
- return {
408
- objectAttributes,
409
- resultHTML
410
- };
411
- };
412
- var generateClientPageData = async (pageLocation, state, objectAttributes, pageLoadHooks, DIST_DIR, pageName) => {
413
- const pageDiff = path.relative(DIST_DIR, pageLocation);
414
- let clientPageJSText = `${globalThis.__SERVER_PAGE_DATA_BANNER__}
415
- /*ELEGANCE_JS*/
416
- let url="${pageDiff === "" ? "/" : `/${pageDiff}`}";`;
417
- {
418
- clientPageJSText += `export const data = {`;
419
- if (state) {
420
- const nonBoundState = state.filter((subj) => subj.bind === void 0);
421
- clientPageJSText += `state:[`;
422
- for (const subject of nonBoundState) {
423
- if (typeof subject.value === "string") {
424
- const stringified = JSON.stringify(subject.value);
425
- clientPageJSText += `{id:${subject.id},value:${stringified}},`;
426
- } else if (typeof subject.value === "function") {
427
- clientPageJSText += `{id:${subject.id},value:${subject.value.toString()}},`;
428
- } else {
429
- clientPageJSText += `{id:${subject.id},value:${JSON.stringify(subject.value)}},`;
430
- }
431
- }
432
- clientPageJSText += `],`;
433
- const formattedBoundState = {};
434
- const stateBinds = state.map((subj) => subj.bind).filter((bind) => bind !== void 0);
435
- for (const bind of stateBinds) {
436
- formattedBoundState[bind] = [];
437
- }
438
- ;
439
- const boundState = state.filter((subj) => subj.bind !== void 0);
440
- for (const subject of boundState) {
441
- const bindingState = formattedBoundState[subject.bind];
442
- delete subject.bind;
443
- bindingState.push(subject);
444
- }
445
- const bindSubjectPairing = Object.entries(formattedBoundState);
446
- if (bindSubjectPairing.length > 0) {
447
- clientPageJSText += "binds:{";
448
- for (const [bind, subjects] of bindSubjectPairing) {
449
- clientPageJSText += `${bind}:[`;
450
- for (const subject of subjects) {
451
- if (typeof subject.value === "string") {
452
- clientPageJSText += `{id:${subject.id},value:${JSON.stringify(subject.value)}},`;
453
- } else {
454
- clientPageJSText += `{id:${subject.id},value:${JSON.stringify(subject.value)}},`;
455
- }
456
- }
457
- clientPageJSText += "]";
458
- }
459
- clientPageJSText += "},";
460
- }
461
- }
462
- const stateObjectAttributes = objectAttributes.filter((oa) => oa.type === 1 /* STATE */);
463
- if (stateObjectAttributes.length > 0) {
464
- const processed = [...stateObjectAttributes].map((soa) => {
465
- delete soa.type;
466
- return soa;
467
- });
468
- clientPageJSText += `soa:${JSON.stringify(processed)},`;
469
- }
470
- const observerObjectAttributes = objectAttributes.filter((oa) => oa.type === 2 /* OBSERVER */);
471
- if (observerObjectAttributes.length > 0) {
472
- let observerObjectAttributeString = "ooa:[";
473
- for (const observerObjectAttribute of observerObjectAttributes) {
474
- const ooa = observerObjectAttribute;
475
- observerObjectAttributeString += `{key:${ooa.key},attribute:"${ooa.attribute}",update:${ooa.update.toString()},`;
476
- observerObjectAttributeString += `refs:[`;
477
- for (const ref of ooa.refs) {
478
- observerObjectAttributeString += `{id:${ref.id}`;
479
- if (ref.bind !== void 0) observerObjectAttributeString += `,bind:${ref.bind}`;
480
- observerObjectAttributeString += "},";
481
- }
482
- observerObjectAttributeString += "]},";
483
- }
484
- observerObjectAttributeString += "],";
485
- clientPageJSText += observerObjectAttributeString;
486
- }
487
- if (pageLoadHooks.length > 0) {
488
- clientPageJSText += "lh:[";
489
- for (const loadHook of pageLoadHooks) {
490
- const key = loadHook.bind;
491
- clientPageJSText += `{fn:${loadHook.fn},bind:"${key || ""}"},`;
492
- }
493
- clientPageJSText += "],";
494
- }
495
- clientPageJSText += `};`;
496
- }
497
- clientPageJSText += "if(!globalThis.pd) { globalThis.pd = {}; globalThis.pd[url] = data}";
498
- const pageDataPath = path.join(pageLocation, `${pageName}_data.js`);
499
- let sendHardReloadInstruction = false;
500
- const transformedResult = await esbuild.transform(clientPageJSText, { minify: true }).catch((error) => {
501
- console.error("Failed to transform client page js!", error);
502
- });
503
- if (!transformedResult) return { sendHardReloadInstruction };
504
- fs.writeFileSync(pageDataPath, transformedResult.code, "utf-8");
505
- return { sendHardReloadInstruction };
506
- };
507
- var buildDynamicPage = async (filePath, DIST_DIR, req, res) => {
508
- let pageElements;
509
- let metadata;
510
- initializeState();
511
- initializeObjectAttributes();
512
- resetLoadHooks();
513
- globalThis.__SERVER_PAGE_DATA_BANNER__ = "";
514
- globalThis.__SERVER_CURRENT_STATE_ID__ = 1;
515
- let modules = [];
516
- try {
517
- const {
518
- construct
519
- } = await import("file://" + filePath);
520
- const {
521
- page,
522
- metadata: pageMetadata,
523
- isDynamicPage,
524
- requestHook,
525
- requiredClientModules
526
- } = construct();
527
- if (requiredClientModules !== void 0) {
528
- modules = requiredClientModules;
529
- }
530
- if (typeof requestHook === "function") {
531
- if (requestHook.constructor.name === "AsyncFunction") {
532
- const doProcessRequest = await requestHook(req, res);
533
- if (doProcessRequest !== void 0 == doProcessRequest === false) {
534
- return false;
535
- }
536
- } else {
537
- const doProcessRequest = requestHook(req, res);
538
- if (doProcessRequest !== void 0 == doProcessRequest === false) {
539
- return false;
540
- }
541
- }
542
- }
543
- pageElements = page;
544
- metadata = pageMetadata;
545
- if (isDynamicPage === false) {
546
- throw new Error("Cannot dynamically render a non-dynamic page.");
547
- }
548
- } catch (e) {
549
- throw `${filePath} - ${e}
550
- ${e?.stack ?? "No stack."}
551
-
552
- `;
553
- }
554
- if (!metadata || metadata && typeof metadata !== "function") {
555
- console.warn(`WARNING: Dynamic ${filePath} does not export a metadata function. This is *highly* recommended.`);
556
- }
557
- if (!pageElements) {
558
- console.warn(`WARNING: Dynamic ${filePath} should export a const page, which is of type BuiltElement<"body">.`);
559
- }
560
- if (typeof pageElements === "function") {
561
- if (pageElements.constructor.name === "AsyncFunction") {
562
- pageElements = await pageElements();
563
- } else {
564
- pageElements = pageElements();
565
- }
566
- }
567
- const state = getState();
568
- const pageLoadHooks = getLoadHooks();
569
- const objectAttributes = getObjectAttributes();
570
- const foundObjectAttributes = await generateSuitablePageElements(
571
- path.dirname(filePath),
572
- pageElements || body(),
573
- metadata ?? (() => head()),
574
- DIST_DIR,
575
- "page",
576
- modules
577
- );
578
- await generateClientPageData(
579
- path.dirname(filePath),
580
- state || {},
581
- [...objectAttributes, ...foundObjectAttributes.objectAttributes],
582
- pageLoadHooks || [],
583
- DIST_DIR,
584
- "page"
585
- );
586
- return foundObjectAttributes.resultHTML;
587
- };
588
- export {
589
- buildDynamicPage,
590
- processPageElements
591
- };
@@ -1,6 +0,0 @@
1
- import { ObjectAttributeType } from "../helpers/ObjectAttributeType";
2
- export declare const getReference: (ref: number) => Element | null;
3
- export declare const createReference: () => {
4
- type: ObjectAttributeType;
5
- value: number;
6
- };
@@ -1,18 +0,0 @@
1
- // src/server/createReference.ts
2
- if (!globalThis.__SERVER_CURRENT_REF_ID__) {
3
- globalThis.__SERVER_CURRENT_REF_ID__ = 0;
4
- }
5
- var currentRefId = globalThis.__SERVER_CURRENT_REF_ID__;
6
- var getReference = (ref) => {
7
- return document.querySelector(`[ref="${ref}]"`);
8
- };
9
- var createReference = () => {
10
- return {
11
- type: 4 /* REFERENCE */,
12
- value: currentRefId++
13
- };
14
- };
15
- export {
16
- createReference,
17
- getReference
18
- };
@@ -1,64 +0,0 @@
1
- import { ObjectAttributeType } from "../helpers/ObjectAttributeType";
2
- type ClientSubjectGeneric<T> = Omit<ClientSubject, "value"> & {
3
- value: T;
4
- };
5
- type Widen<T> = T extends number ? number : T extends string ? string : T extends boolean ? boolean : T extends {} ? T & Record<string, any> : T;
6
- export declare const createState: <U extends number | string | boolean | {}>(value: U, options?: {
7
- bind?: number;
8
- }) => {
9
- id: number;
10
- value: Widen<U>;
11
- type: ObjectAttributeType.STATE;
12
- bind: string | undefined;
13
- };
14
- type Dependencies = {
15
- type: ObjectAttributeType;
16
- value: unknown;
17
- id: number;
18
- bind?: string;
19
- }[];
20
- type Parameters = {};
21
- export type SetEvent<E, CT> = Omit<Parameters, "event"> & {
22
- event: Omit<E, "currentTarget"> & {
23
- currentTarget: CT;
24
- };
25
- };
26
- export type CreateEventListenerOptions<D extends Dependencies, P extends {} = {}> = {
27
- dependencies?: [...D] | [];
28
- eventListener: (params: P & {
29
- event: Event;
30
- }, ...subjects: {
31
- [K in keyof D]: ClientSubjectGeneric<D[K]["value"]>;
32
- }) => void;
33
- params?: P | null;
34
- };
35
- export declare const createEventListener: <D extends Dependencies, P extends Parameters>({ eventListener, dependencies, params, }: CreateEventListenerOptions<D, P>) => {
36
- id: number;
37
- type: ObjectAttributeType;
38
- value: Function;
39
- };
40
- export declare const initializeState: () => void;
41
- export declare const getState: () => {
42
- value: unknown;
43
- type: ObjectAttributeType;
44
- id: number;
45
- bind?: number;
46
- }[];
47
- export declare const initializeObjectAttributes: () => never[];
48
- export declare const getObjectAttributes: () => ({
49
- type: ObjectAttributeType;
50
- id: string | number;
51
- value: any;
52
- bind?: string;
53
- } | {
54
- type: ObjectAttributeType;
55
- refs: {
56
- id: number;
57
- bind?: string;
58
- }[];
59
- initialValues: any[];
60
- update: (...value: any) => any;
61
- } | {
62
- type: ObjectAttributeType;
63
- })[];
64
- export {};