Skip to content
This repository has been archived by the owner on Mar 11, 2024. It is now read-only.

Commit

Permalink
feat: initial code
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurfiorette committed Jan 21, 2024
1 parent e02a371 commit f87a3b8
Show file tree
Hide file tree
Showing 12 changed files with 501 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Kita

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
123 changes: 123 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/// <reference path="./types/index.d.ts" />
/* global SUSPENSE_ROOT */
'use strict';

const fp = require('fastify-plugin');
const { pipeHtml } = require('@kitajs/html/suspense');
const { prependDoctype } = require('./lib/prepend-doctype');
const { isHtml } = require('./lib/is-html');
const { CONTENT_TYPE_HEADER } = require('./lib/constants');

/**
* @type {import('fastify').FastifyPluginCallback<import('./types').FastifyKitaHtmlOptions>}
*/
function fastifyKitaHtml(fastify, opts, next) {
// Good defaults
opts.autoDetect ??= false;
opts.autoDoctype ??= true;
opts.contentType ??= 'text/html; charset=utf8';
opts.isHtml ??= isHtml;

// Enables suspense if it's not enabled yet
SUSPENSE_ROOT.enabled ||= true;

// The normal .html handler is much simpler than the streamHtml one
fastify.decorateReply('html', html);

// As JSX is evaluated from the inside out, renderToStream() method requires
// a function to be able to execute some code before the JSX calls gets to
// render, it can be avoided by simply executing the code in the
// streamHtml getter method.
fastify.decorateReply('streamHtml', {
getter() {
SUSPENSE_ROOT.requests.set(this.request.id, {
// As reply.raw is a instance of Writable, we can use it instead of
// creating a our own new stream.
stream: new WeakRef(this.raw),
running: 0,
sent: false
});

return streamHtml;
}
});

// The onSend hook is only used by autoDetect, so we can
// skip adding it if it's not enabled.
if (opts.autoDetect) {
fastify.addHook('onSend', onSend);
}

return next();

/**
* @type {import('fastify').FastifyReply['html']}
*/
function html(html) {
this.header(CONTENT_TYPE_HEADER, opts.contentType);

if (opts.autoDoctype) {
// Handles possibility of html being a promise
if (html instanceof Promise) {
html = html.then(prependDoctype);
} else {
html = prependDoctype(html);
}
}

return this.send(html);
}

/**
* @type {import('fastify').FastifyReply['streamHtml']}
*/
function streamHtml(html) {
this.header(CONTENT_TYPE_HEADER, opts.contentType);

if (opts.autoDoctype) {
// Handles possibility of html being a promise
if (html instanceof Promise) {
html = html.then(prependDoctype);
} else {
html = prependDoctype(html);
}
}

// Hijacks the reply stream, so we can control when the stream is ended.
this.hijack();

// When the .streamHtml is called, the fastify decorator's getter method
// already created the request data at the SUSPENSE_ROOT for us, so we
// can simply pipe the first html wave to the reply stream.
pipeHtml(html, this.raw, this.request.id);

// The reply stream will be ended when the suspense root is resolved.
return this;
}

/**
* @type {import('fastify').onSendHookHandler}
*/
function onSend(_request, reply, payload, done) {
// Streamed html should also return false here, because it's not a string,
// and already was handled by the streamHtml method.
if (opts.isHtml(payload)) {
reply.header(CONTENT_TYPE_HEADER, opts.contentType);

if (opts.autoDoctype) {
// Payload will never be a promise here, because the content was already
// serialized.
payload = prependDoctype(payload);
}
}

return done(null, payload);
}
}

module.exports = fp(fastifyKitaHtml, {
fastify: '4.x',
name: '@kitajs/fastify-html-plugin'
});
module.exports.default = fastifyKitaHtml;
module.exports.fastifyKitaHtml = fastifyKitaHtml;
5 changes: 5 additions & 0 deletions lib/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports.HTML_TAG = '<html';

module.exports.HTML_TAG_LENGTH = module.exports.HTML_TAG.length;

module.exports.CONTENT_TYPE_HEADER = 'content-type';
25 changes: 25 additions & 0 deletions lib/is-html.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* There's no real way to validate HTML, so this is a best guess.
*
* @see https://stackoverflow.com/q/1732348
* @see https://stackoverflow.com/q/11229831
*
* @this {void}
* @param {string} value
* @returns {value is string}
*/
module.exports.isHtml = function isHtml (value) {
if (typeof value !== 'string') { return false }

value = value.trim()
const length = value.length

return (
// Minimum html is 7 characters long: <a></a>
length >= 7 &&
// open tag
value[0] === '<' &&
// close tag
value[length - 1] === '>'
)
}
21 changes: 21 additions & 0 deletions lib/is-tag-html.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const { HTML_TAG_LENGTH, HTML_TAG } = require("./constants")


/**
* Returns true if the string starts with `<html`, **ignores whitespace and
* casing**.
*
* @param {string} value
* @this {void}
*/
module.exports.isTagHtml = function isTagHtml (value) {
return (
value
// remove whitespace from the start of the string
.trimStart()
// get the first 5 characters
.slice(0, HTML_TAG_LENGTH)
// compare to `<html`
.toLowerCase() === HTML_TAG
)
}
18 changes: 18 additions & 0 deletions lib/prepend-doctype.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { isTagHtml } = require('./is-tag-html')

/**
* Prepends doctype only in full html strings, because routes that returns only
* a fragment of html (a.k.a components or partials) should not have a doctype
* attached to them.
*
* @param {string} html
* @returns {string}
*/
module.exports.prependDoctype = function prependDoctype (html) {
// Starts with <html
if (isTagHtml(html)) {
return '<!doctype html>' + html
}

return html
}
43 changes: 43 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"name": "@kitajs/fastify-html-plugin",
"version": "1.0.0",
"description": "A Fastify plugin to add support for @kitajs/html",
"main": "index.js",
"type": "commonjs",
"types": "types/index.d.ts",
"scripts": {
"lint": "standard --verbose | snazzy",
"test": "npm run test:unit && npm run test:typescript",
"test:unit": "tap",
"test:typescript": "tsd"
},
"pre-commit": [
"lint",
"test"
],
"repository": {
"type": "git",
"url": "git+https://github.com/kitajs/fastify-html-plugin.git"
},
"author": "Arthur Fiorette <[email protected]>",
"license": "MIT",
"bugs": {
"url": "https://github.com/kitajs/fastify-html-plugin/issues"
},
"homepage": "https://github.com/kitajs/fastify-html-plugin#readme",
"devDependencies": {
"@fastify/pre-commit": "^2.0.2",
"@types/node": "^20.11.5",
"fastify": "^4.0.0-rc.2",
"snazzy": "^9.0.0",
"standard": "^17.0.0",
"tap": "^16.0.0"
},
"dependencies": {
"@kitajs/html": "^3.0.11",
"fastify-plugin": "^4.0.0"
},
"publishConfig": {
"access": "public"
}
}
32 changes: 32 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const { h } = require('@kitajs/html');
const { Suspense } = require('@kitajs/html/suspense');
const fastify = require('fastify');
const fastifyKitaHtml = require('./');

const app = fastify();

app.register(fastifyKitaHtml);

// 3x faster than React, ~71.61 µs to generate entire MDN homepage (66.7Kb)
app.get('/', (req, res) =>
res.streamHtml(
h(
'html',
null,
h('head', null, h('title', null, '@kitajs/html + fastify')),
h(
'body',
null,
h('h1', null, 'Hello world from JSX!'),

h('div', { 'hx-get': '/htmx', 'hx-trigger': 'load', 'hx-swap': 'outerHTML' })
)
)
)
);

app.get('/htmx', (_, res) =>
res.html(Html.createElement('div', null, 'Hello from Htmx!'))
);

app.listen().then(console.log);
49 changes: 49 additions & 0 deletions test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//@ts-nocheck

import { Html } from '@kitajs/html';
import { Suspense } from '@kitajs/html/suspense';
import fastify from 'fastify';
import fastifyKitaHtml from './';

const app = fastify();

app.register(fastifyKitaHtml);

// 3x faster than React, ~71.61 µs to generate entire MDN homepage (66.7Kb)
app.get('/', (req, res) =>
res.streamHtml(
<html>
<head>
<title>@kitajs/html + fastify</title>
</head>
<body>
<h1>Hello world from JSX!</h1>



<div hx-get='/htmx' hx-trigger='load' hx-swap='outerHTML'></div>
</body>
</html>
)
);

app.get('/htmx', (_, res) => res.html(<div>Hello from Htmx!</div>));

app.listen().then(console.log);

















39 changes: 39 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"compilerOptions": {
"target": "ESNext",
"jsx": "react",
"jsxFactory": "Html.createElement",
"jsxFragmentFactory": "Html.Fragment",
"plugins": [{ "name": "@kitajs/ts-html-plugin" }],
"module": "CommonJS",
"moduleResolution": "node",
"incremental": true,
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"declaration": true,
"importHelpers": true,
"declarationMap": true,
"sourceMap": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"useUnknownInCatchVariables": true,
"alwaysStrict": true,
"outDir": "dist",
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"skipDefaultLibCheck": true
},
"include": ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.d.ts"],
"exclude": ["node_modules", "dist"]
}
Empty file removed types/.gitkeep
Empty file.
Loading

0 comments on commit f87a3b8

Please sign in to comment.