@smuzi/ssr 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 smuzi-ts
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
File without changes
@@ -0,0 +1,11 @@
1
+ import { Option, Result, StdError } from "@smuzi/std";
2
+ type InputData = Record<string, unknown>;
3
+ type SSREngineConfig = {
4
+ pathDir: string;
5
+ extension: string;
6
+ };
7
+ export declare function ssrEngine({ pathDir, extension }?: Partial<SSREngineConfig>): {
8
+ render: (templateName: string, inputData: InputData, slots?: Option) => Promise<Result<string, StdError>>;
9
+ response: (templateName: string, inputData?: InputData) => Promise<string | StdError>;
10
+ };
11
+ export {};
package/build/index.js ADDED
@@ -0,0 +1,139 @@
1
+ import * as fs from "node:fs";
2
+ import { path, None, Err, Ok, transformError, regexp } from "@smuzi/std";
3
+ import * as vm from "node:vm";
4
+ import * as _std from "@smuzi/std";
5
+ function getPath(pathDir, templateName, extension) {
6
+ return path.join(pathDir, templateName + "." + extension);
7
+ }
8
+ async function runSSRCode(context, code) {
9
+ const printFunc = `
10
+ (async () => {
11
+ function _print(html) {
12
+ _output += html
13
+ }`;
14
+ code = `
15
+ _output = '';
16
+ ${printFunc}
17
+ ${code}
18
+ return _output
19
+ })()`;
20
+ const script = new vm.Script(code);
21
+ const result = await script.runInContext(context);
22
+ return Ok(result !== undefined ? String(result) : '');
23
+ }
24
+ function findForBlock(templateCode) {
25
+ const openingDirective = /@for\s*\(\s*([A-Za-z_$][\w$]*)\s+of\s+([^)]+?)\s*\)/g;
26
+ const openingMatch = openingDirective.exec(templateCode);
27
+ if (openingMatch === null || openingMatch.index === undefined) {
28
+ return undefined;
29
+ }
30
+ const bodyStart = openingMatch.index + openingMatch[0].length;
31
+ const directive = /@for\s*\(\s*[A-Za-z_$][\w$]*\s+of\s+[^)]*?\s*\)|@end\b/g;
32
+ directive.lastIndex = bodyStart;
33
+ let depth = 1;
34
+ for (const match of templateCode.matchAll(directive)) {
35
+ if (match[0].startsWith("@for")) {
36
+ depth += 1;
37
+ continue;
38
+ }
39
+ depth -= 1;
40
+ if (depth === 0 && match.index !== undefined) {
41
+ return {
42
+ start: openingMatch.index,
43
+ end: match.index + match[0].length,
44
+ item: openingMatch[1],
45
+ iterable: openingMatch[2],
46
+ body: templateCode.slice(bodyStart, match.index),
47
+ };
48
+ }
49
+ }
50
+ return undefined;
51
+ }
52
+ async function parseCode(context, templateCode) {
53
+ try {
54
+ let renderedTemplate = '';
55
+ let cursor = 0;
56
+ let forBlock;
57
+ while ((forBlock = findForBlock(templateCode.slice(cursor))) !== undefined) {
58
+ const block = {
59
+ ...forBlock,
60
+ start: forBlock.start + cursor,
61
+ end: forBlock.end + cursor,
62
+ };
63
+ renderedTemplate += templateCode.slice(cursor, block.start);
64
+ const code = `
65
+ for (const ${block.item} of (${block.iterable})) {
66
+ const res = await _ssrEngine.parseCode(
67
+ { [${JSON.stringify(block.item)}]: ${block.item} },
68
+ ${JSON.stringify(block.body)}
69
+ );
70
+ _output += res.unwrap();
71
+ }`;
72
+ const renderedBlock = await runSSRCode(context, code);
73
+ if (renderedBlock.isErr()) {
74
+ return renderedBlock;
75
+ }
76
+ renderedBlock.runThenOk(html => renderedTemplate += html);
77
+ cursor = block.end;
78
+ }
79
+ renderedTemplate += templateCode.slice(cursor);
80
+ return await regexp.asyncReplace(renderedTemplate, /{{([\s\S]*?)}}/g, async (match, code) => {
81
+ return await runSSRCode(context, `_print(${code})`);
82
+ });
83
+ // const res1 = Ok(
84
+ // templateCode
85
+ // //@if(condition)...@else...@end or @if(condition)...@end
86
+ // .replace(/@if\s*\(\s*([^)]+)\s*\)([\s\S]*?)(?:@else([\s\S]*?))?@end/g, (match, condition, ifBody, elseBody) => {
87
+ // const code = `
88
+ // _print((${condition}) ? \`${ifBody.replace(/`/g, '\\`').replace(/\$/g, '\\$')}\` : \`${(elseBody || '').replace(/`/g, '\\`').replace(/\$/g, '\\$')}\`);
89
+ // `;
90
+ // return runSSRCode(context, code);
91
+ // })
92
+ // //<script ssr>...</script>
93
+ // .replace(/<script\b[^>]*\bssr>([\s\S]*?)<\/script>/g, (match, code) => runSSRCode(context, code))
94
+ //
95
+ // //{{ ... }}
96
+ // .replace(/{{([\s\S]*?)}}/g, (match, code) => {
97
+ // return runSSRCode(context, `_print(${code})`)
98
+ // })
99
+ // );
100
+ }
101
+ catch (err) {
102
+ return Err(transformError(err));
103
+ }
104
+ }
105
+ function createContext(inputData, pathDir, extension) {
106
+ return vm.createContext({
107
+ ...inputData,
108
+ _std,
109
+ _output: '',
110
+ _ssrEngine: {
111
+ renderComponent: async (templateNameChild, inputDataChild) => {
112
+ return (renderTemplate(pathDir, extension))(templateNameChild, inputDataChild);
113
+ },
114
+ parseCode: async (inputDataChild, templateCode) => {
115
+ return parseCode(createContext(Object.assign(inputDataChild, inputData), pathDir, extension), templateCode);
116
+ }
117
+ },
118
+ });
119
+ }
120
+ function renderTemplate(pathDir, extension) {
121
+ return async (templateName, inputData = {}, slots = None()) => {
122
+ let templateCode = fs.readFileSync(getPath(pathDir, templateName, extension), 'utf-8');
123
+ const context = createContext(inputData, pathDir, extension);
124
+ return parseCode(context, templateCode);
125
+ };
126
+ }
127
+ export function ssrEngine({ pathDir = "./src/templates", extension = "html" } = {}) {
128
+ const render = renderTemplate(pathDir, extension);
129
+ const response = async (templateName, inputData = {}) => {
130
+ return (await render(templateName, inputData)).match({
131
+ Err: err => err,
132
+ Ok: html => html,
133
+ });
134
+ };
135
+ return {
136
+ render,
137
+ response,
138
+ };
139
+ }
package/globals.d.ts ADDED
@@ -0,0 +1,8 @@
1
+
2
+ declare global {
3
+ function _print(value: string): void;
4
+
5
+ const _std: typeof import("@smuzi/std");
6
+ }
7
+
8
+ export {};
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@smuzi/ssr",
3
+ "version": "0.0.1",
4
+ "description": "Simple template engine for generation HTML pages with advanced syntaxes",
5
+ "type": "module",
6
+ "types": "./build/index.d.ts",
7
+ "keywords": [
8
+ "ssr",
9
+ "ssg",
10
+ "server side rendering",
11
+ "template",
12
+ "html",
13
+ "render",
14
+ "view"
15
+ ],
16
+ "author": "Denis Ratushniak <dinisimys2018@gmail.com>",
17
+ "license": "MIT",
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "files": [
22
+ "./src",
23
+ "./build",
24
+ "globals.d.ts"
25
+ ],
26
+ "exports": {
27
+ "./package.json": "./package.json",
28
+ ".": "./src/index.ts",
29
+ "./globals.d.ts": "./globals.d.ts",
30
+ "./*": "./src/*.ts"
31
+ },
32
+ "imports": {
33
+ "#lib/*": "./src/*"
34
+ },
35
+ "dependencies": {
36
+ "@smuzi/std": "0.2.5"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^22.15.21",
40
+ "tsx": "^4.20.6",
41
+ "typescript": "^7.0.2",
42
+ "@smuzi/tests": "0.0.2",
43
+ "@smuzi/faker": "0.0.4"
44
+ },
45
+ "scripts": {
46
+ "test": "tsx tests/index.ts",
47
+ "build": "tsc --project tsconfig.build.json"
48
+ }
49
+ }
@@ -0,0 +1,10 @@
1
+
2
+ declare global {
3
+ function _print(value: string): void;
4
+ async function _component(component: string, slots: Record<string, () => string>): Promise;
5
+ async function _component(component: string): Promise;
6
+
7
+ const _std: typeof import("@smuzi/std");
8
+ }
9
+
10
+ export {};
package/src/index.ts ADDED
@@ -0,0 +1,212 @@
1
+ import * as fs from "node:fs";
2
+ import {
3
+ uuid,
4
+ HttpResponse,
5
+ path,
6
+ ResponseHttpHeaders,
7
+ Some,
8
+ None,
9
+ Option,
10
+ dump,
11
+ Result,
12
+ Err,
13
+ Ok,
14
+ transformError, StdError, panic, Pipe, regexp
15
+ } from "@smuzi/std";
16
+ import * as vm from "node:vm";
17
+
18
+ import * as _std from "@smuzi/std"
19
+
20
+ function getPath(pathDir: string, templateName: string, extension: string) {
21
+ return path.join(pathDir, templateName + "." + extension)
22
+ }
23
+
24
+ type InputData = Record<string, unknown>
25
+
26
+ type SSREngineConfig = {
27
+ pathDir: string,
28
+ extension: string,
29
+ }
30
+
31
+ async function runSSRCode(context, code: string): Promise<Result<string, StdError>> {
32
+ const printFunc = `
33
+ (async () => {
34
+ function _print(html) {
35
+ _output += html
36
+ }`;
37
+ code = `
38
+ _output = '';
39
+ ${printFunc}
40
+ ${code}
41
+ return _output
42
+ })()`
43
+ const script = new vm.Script(code);
44
+
45
+ const result = await script.runInContext(context);
46
+
47
+ return Ok(result !== undefined ? String(result) : '');
48
+ }
49
+
50
+ type ForBlock = {
51
+ start: number,
52
+ end: number,
53
+ item: string,
54
+ iterable: string,
55
+ body: string,
56
+ }
57
+
58
+ function findForBlock(templateCode: string): ForBlock | undefined {
59
+ const openingDirective = /@for\s*\(\s*([A-Za-z_$][\w$]*)\s+of\s+([^)]+?)\s*\)/g;
60
+ const openingMatch = openingDirective.exec(templateCode);
61
+
62
+ if (openingMatch === null || openingMatch.index === undefined) {
63
+ return undefined;
64
+ }
65
+
66
+ const bodyStart = openingMatch.index + openingMatch[0].length;
67
+ const directive = /@for\s*\(\s*[A-Za-z_$][\w$]*\s+of\s+[^)]*?\s*\)|@end\b/g;
68
+ directive.lastIndex = bodyStart;
69
+
70
+ let depth = 1;
71
+ for (const match of templateCode.matchAll(directive)) {
72
+ if (match[0].startsWith("@for")) {
73
+ depth += 1;
74
+ continue;
75
+ }
76
+
77
+ depth -= 1;
78
+ if (depth === 0 && match.index !== undefined) {
79
+ return {
80
+ start: openingMatch.index,
81
+ end: match.index + match[0].length,
82
+ item: openingMatch[1],
83
+ iterable: openingMatch[2],
84
+ body: templateCode.slice(bodyStart, match.index),
85
+ };
86
+ }
87
+ }
88
+
89
+ return undefined;
90
+ }
91
+
92
+ async function parseCode(context: any, templateCode: string) {
93
+ try {
94
+ let renderedTemplate = '';
95
+ let cursor = 0;
96
+ let forBlock: ForBlock | undefined;
97
+
98
+ while ((forBlock = findForBlock(templateCode.slice(cursor))) !== undefined) {
99
+ const block = {
100
+ ...forBlock,
101
+ start: forBlock.start + cursor,
102
+ end: forBlock.end + cursor,
103
+ };
104
+
105
+ renderedTemplate += templateCode.slice(cursor, block.start);
106
+
107
+ const code = `
108
+ for (const ${block.item} of (${block.iterable})) {
109
+ const res = await _ssrEngine.parseCode(
110
+ { [${JSON.stringify(block.item)}]: ${block.item} },
111
+ ${JSON.stringify(block.body)}
112
+ );
113
+ _output += res.unwrap();
114
+ }`;
115
+ const renderedBlock = await runSSRCode(context, code);
116
+
117
+ if (renderedBlock.isErr()) {
118
+ return renderedBlock;
119
+ }
120
+
121
+ renderedBlock.runThenOk(html => renderedTemplate += html);
122
+ cursor = block.end;
123
+ }
124
+
125
+ renderedTemplate += templateCode.slice(cursor);
126
+
127
+ return await regexp.asyncReplace(renderedTemplate, /{{([\s\S]*?)}}/g, async (match, code) => {
128
+ return await runSSRCode(context, `_print(${code})`)
129
+ });
130
+
131
+
132
+ // const res1 = Ok(
133
+ // templateCode
134
+ // //@if(condition)...@else...@end or @if(condition)...@end
135
+ // .replace(/@if\s*\(\s*([^)]+)\s*\)([\s\S]*?)(?:@else([\s\S]*?))?@end/g, (match, condition, ifBody, elseBody) => {
136
+ // const code = `
137
+ // _print((${condition}) ? \`${ifBody.replace(/`/g, '\\`').replace(/\$/g, '\\$')}\` : \`${(elseBody || '').replace(/`/g, '\\`').replace(/\$/g, '\\$')}\`);
138
+ // `;
139
+ // return runSSRCode(context, code);
140
+ // })
141
+ // //<script ssr>...</script>
142
+ // .replace(/<script\b[^>]*\bssr>([\s\S]*?)<\/script>/g, (match, code) => runSSRCode(context, code))
143
+ //
144
+ // //{{ ... }}
145
+ // .replace(/{{([\s\S]*?)}}/g, (match, code) => {
146
+ // return runSSRCode(context, `_print(${code})`)
147
+ // })
148
+ // );
149
+ } catch (err) {
150
+ return Err(transformError(err));
151
+ }
152
+ }
153
+
154
+ function createContext(inputData, pathDir, extension )
155
+ {
156
+ return vm.createContext({
157
+ ...inputData,
158
+ _std,
159
+ _output: '',
160
+ _ssrEngine: {
161
+ renderComponent: async (templateNameChild: string, inputDataChild) => {
162
+ return (renderTemplate(pathDir, extension))(templateNameChild, inputDataChild)
163
+ },
164
+ parseCode: async (inputDataChild, templateCode) => {
165
+ return parseCode(
166
+ createContext(
167
+ Object.assign(inputDataChild, inputData),
168
+ pathDir,
169
+ extension
170
+ ), templateCode)
171
+ }
172
+ },
173
+ })
174
+ }
175
+
176
+ function renderTemplate(
177
+ pathDir: string,
178
+ extension: string,
179
+ ): ( templateName: string,
180
+ inputData: InputData,
181
+ slots?: Option
182
+ ) => Promise<Result<string, StdError>> {
183
+ return async (
184
+ templateName: string,
185
+ inputData: InputData = {},
186
+ slots: Option = None()
187
+ ) => {
188
+
189
+ let templateCode = fs.readFileSync(getPath(pathDir, templateName, extension), 'utf-8');
190
+
191
+ const context = createContext(inputData, pathDir, extension);
192
+
193
+ return parseCode(context, templateCode);
194
+ }
195
+ }
196
+
197
+ export function ssrEngine({pathDir = "./src/templates", extension = "html"}: Partial<SSREngineConfig> = {}) {
198
+
199
+ const render = renderTemplate(pathDir, extension)
200
+
201
+ const response = async (templateName: string, inputData: InputData = {}) => {
202
+ return (await render(templateName, inputData)).match({
203
+ Err: err => err,
204
+ Ok: html => html,
205
+ });
206
+ }
207
+
208
+ return {
209
+ render,
210
+ response,
211
+ }
212
+ }