Compare commits

..

12 commits

81 changed files with 11333 additions and 4369 deletions

View file

@ -6,6 +6,6 @@
**/*.yml
**/*.yaml
templates/**
templates
**/public/*

View file

@ -8,6 +8,7 @@
"hookable",
"mcfly",
"mcflyjs",
"nitropack",
"ultrahtml",
"unstorage"
],

4
CHANGESET.md Normal file
View file

@ -0,0 +1,4 @@
# Rough list of changes
1. Expose a `McFly` object containing event properties to `server:setup` scripts. Useful for handling requests like form submission.
2. Add a cozy demo page for form handling using the exposed `McFly` object

View file

@ -19,7 +19,50 @@ To start or participate on discussions, see our [mcfly-discussions](https://list
## Contribute Code
Due to still figuring out how parts fit together, we are not ready for code contributions.
We use `git` and `email` here -- it is actually fun!
To get started, setup [git send-email](https://git-send-email.io).
After setting up `git send-email` you can now follow the steps below to start hacking:
1⃣ Clone the repository to your local machine, then go into the project directory:
```bash
$ git clone https://git.sr.ht/~ayoayco/mcfly
$ cd mcfly
```
2⃣ Create a new branch for your changes:
```bash
$ git checkout -b my-branch
```
3⃣ Make your changes, and then commit them with a descriptive message using [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/):
```bash
$ git commit -m "feat(core): implement server-side rendering"
```
4⃣ Use `git send-email` to send a patch:
```bash
$ git send-email --to="~ayoayco/mcfly-patches@lists.sr.ht" HEAD^
```
### Tips:
💡 You can set the default "to" address for the project:
```bash
$ git config sendemail.to "~ayoayco/mcfly-patches@lists.sr.ht"
```
💡 The `HEAD^` bit is a reference to the latest commit, which will be added to your patch. This could be a range of commits as well if you have mutiple commits.
5⃣ After successfully sending your patch, wait for a response from us whether the patch needs rework... or a notification if it gets merged!
> As a summary, we use `git` and `email` to collaborate on McFly. You have to set up [git send-email](https://git-send-email.io) and send patches via email. :)
## Get in touch

View file

@ -1,5 +1,5 @@
<p align="center">
<img width="250" src="https://git.ayo.run/ayo/mcfly/raw/branch/main/assets/mcfly-logo-sm.png" alt="McFly logo" />
<img width="250" src="https://git.sr.ht/~ayoayco/mcfly/blob/main/assets/mcfly-logo-sm.png" alt="McFly logo" />
</p>
<h1 align="center">McFly</h1>
@ -27,15 +27,9 @@ I thought:
## Project Status
We are currently in a focused rewrite. All parts are subject to breaking changes in minor releases.
We are currently in a Proof of Concept phase. All parts are subject to breaking changes in minor releases.
- [x] generic plugin system for using server frameworks
- [x] file-based API routing via fastify as server framework
- [ ] file-based HTML pages routing
- [ ] HTML templating via Eta
- [ ] auto-registry of custom elements
- [ ] SSR custom elements
- [ ] SSG builds
👉 [Road to v1.0.0 todo items](https://github.com/ayoayco/McFly/issues?q=is%3Aissue%20state%3Aopen%20milestone%3Av1.0.0)
## Try it today
@ -45,7 +39,15 @@ Run the following to generate a McFly starter project.
npm create mcfly@latest
```
## Target Features
## How it works (for the nerds)
It is primarily a runtime middleware for [Nitro](https://nitro.build). Every time a page is requested, the McFly middleware intercepts and assembles the view for the requestor. McFly does this with the assets it knows about which are mostly: pages, components, public assets. Additionally, Nitro is also capable of generating static assets on build time.
These patterns are commonly referred to as Server-Side Rendering and Static Site Generation (SSR & SSG).
The idea is to have a plugin system which allows for the core functionality to only "lean" on web platform features. Anything not yet a standard is implemented as a plugin which will be easily "swapped" away when the platform catches up.
## Features
✅ Use vanilla custom elements (or sugar-coated web components)<br>
✅ Write server-powered .html pages<br>
@ -55,7 +57,19 @@ npm create mcfly@latest
## Special directories
**1. `./src/api/`**
**1. `./src/pages/`**
- file-based routing for `.html` files
- directly use custom elements & static fragments (no imports or registry maintenance needed)
- use `<script server:setup>` to define logic that runs on the server, which then gets stripped away
**2. `./src/components/`**
- custom element constructor files (only `.js` files for now)
- all components are automatically registered using their file names; a `hello-world.js` component can be used as `<hello-world>`
- static `.html` fragments; a `my-header.html` fragment can be directly used as `<my-header>`
**3. `./src/api/`**
- file-based routing for REST API endpoints
- e.g., `./src/api/users.js` can be accessed via `http://<domain>/api/users`
@ -65,10 +79,9 @@ npm create mcfly@latest
The following are the project packages published on the NPM registry:
| Package | Description | Version |
| :------------------------------------------------------- | --------------------------------------------- | ---------------------------------------------------------------------- |
| [`@mcflyjs/config`](https://ayco.io/n/@mcflyjs/config) | Configuration handling for McFly projects | ![npm version](https://img.shields.io/npm/v/%40mcflyjs%2Fconfig/alpha) |
| [`@mcflyjs/core`](https://ayco.io/n/@mcflyjs/core) | Commands & runtime handling | ![npm version](https://img.shields.io/npm/v/%40mcflyjs%2Fcore/alpha) |
| [`@mcflyjs/fastify`](https://ayco.io/n/@mcflyjs/fastify) | Adapter for using fastify as server framework | ![npm version](https://img.shields.io/npm/v/%40mcflyjs%2Ffastify) |
| :----------------------------------------------------- | -------------------------------------------- | ---------------------------------------------------------------- |
| [`@mcflyjs/config`](https://ayco.io/n/@mcflyjs/config) | Nitro server config for McFly projects | ![npm version](https://img.shields.io/npm/v/%40mcflyjs%2Fconfig) |
| [`@mcflyjs/core`](https://ayco.io/n/@mcflyjs/core) | Route event and config handlers | ![npm version](https://img.shields.io/npm/v/%40mcflyjs%2Fcore) |
| [`create-mcfly`](https://ayco.io/n/create-mcfly) | Script for scaffolding a new McFly workspace | ![npm version](https://img.shields.io/npm/v/create-mcfly) |
## Project setup
@ -91,9 +104,9 @@ The following commands are available to you on this project. Add more, or modify
## More info
This framework was initially a result of [an exploration](https://social.ayco.io/@ayo/111195315785886977) for using [Nitro](https://nitro.build) and custom elements using a minimal [Web Component Base](https://WebComponent.io) class.
This framework is a result of [an exploration](https://social.ayco.io/@ayo/111195315785886977) for using [Nitro](https://nitro.build) and custom elements using a minimal [Web Component Base](https://WebComponent.io) class.
In 2026, we pivoted to a new target architecture to become more like a "glue" that allows putting together existing options that achieve our goals. We avoid building custom mechanisms when we can. The resulting architecture theoretically allows using different server frameworks, templating libraries, custom element libraries, etc.
**Nitro** is the same production-grade web server powering [Nuxt](https://nuxt.com/)
---

3
VALUES.md Normal file
View file

@ -0,0 +1,3 @@
# Values (initial)
Our core values include leaning on open standards and decentralized technologies, which do not require any form of lock-in. Therefore, you dont need anything else than `git` and `email` to collaborate.

View file

@ -1,6 +0,0 @@
import { defineConfig } from '@mcflyjs/config'
import fastify from '@mcflyjs/fastify'
export default defineConfig({
server: fastify(),
})

View file

@ -1,17 +0,0 @@
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "mcfly serve"
},
"author": "",
"license": "ISC",
"dependencies": {
"@mcflyjs/core": "workspace:*",
"@mcflyjs/config": "workspace:*",
"@mcflyjs/fastify": "workspace:*"
}
}

View file

@ -1,29 +0,0 @@
# Routes Folder
Routes define the pathways within your application.
Fastify's structure supports the modular monolith approach, where your
application is organized into distinct, self-contained modules.
This facilitates easier scaling and future transition to a microservice architecture.
In the future you might want to independently deploy some of those.
In this folder you should define all the routes that define the endpoints
of your web application.
Each service is a [Fastify
plugin](https://fastify.dev/docs/latest/Reference/Plugins/), it is
encapsulated (it can have its own independent plugins) and it is
typically stored in a file; be careful to group your routes logically,
e.g. all `/users` routes in a `users.js` file. We have added
a `root.js` file for you with a '/' root added.
If a single file becomes too large, create a folder and add a `index.js` file there:
this file must be a Fastify plugin, and it will be loaded automatically
by the application. You can now add as many files as you want inside that folder.
In this way you can create complex routes within a single monolith,
and eventually extract them.
If you need to share functionality between routes, place that
functionality into the `plugins` folder, and share it via
[decorators](https://fastify.dev/docs/latest/Reference/Decorators/).
If you're a bit confused about using `async/await` to write routes, you would
better take a look at [Promise resolution](https://fastify.dev/docs/latest/Reference/Routes/#promise-resolution) for more details.

View file

@ -1,6 +0,0 @@
export default async (fastify) => {
fastify.get('/', async function (request, reply) {
console.log({ request, reply })
return 'This is an example'
})
}

View file

@ -1,5 +0,0 @@
export default async (fastify) => {
fastify.get('/', async function (request, reply) {
return 'This is the API Index'
})
}

View file

@ -1,6 +0,0 @@
export default async function (fastify, opts) {
fastify.get('/', async function (request, reply) {
console.log({ opts, request, reply })
return { root: true }
})
}

View file

@ -16,7 +16,7 @@ export default [
eslintPluginPrettierRecommended,
includeIgnoreFile(gitignorePath),
{
ignores: ['site/*', 'templates/**', '**/public/*', 'demo/*'],
ignores: ['site/*', 'templates/*', '**/public/*'],
},
{
rules: {

View file

@ -2,17 +2,16 @@
"name": "mcfly-monorepo",
"private": true,
"scripts": {
"postinstall": "pnpm -F @mcflyjs/core build && pnpm -F @mcflyjs/config build",
"preinstall": "npx only-allow pnpm && pnpm -F @mcflyjs/core build && pnpm -F @mcflyjs/config build",
"start": "pnpm run site",
"dev": "pnpm run site",
"demo": "pnpm run build:deps && pnpm -F demo start",
"site": "pnpm run build:deps && pnpm -F site start",
"site": "pnpm -F @mcflyjs/core run build && pnpm -F @mcflyjs/config run build && pnpm --filter site start",
"build": "pnpm -F './packages/**' build",
"build:deps": "pnpm -F @mcflyjs/core build && pnpm -F @mcflyjs/config build",
"build:site": "pnpm -F site build",
"build:site:preview": "pnpm -F site build:preview",
"template:basic": "pnpm run build && pnpm -F basic-template start",
"create:mcfly": "node ./packages/create-mcfly",
"create:component": "node ./packages/create-component",
"cli": "node ./packages/core/cli/index.js",
"test": "vitest --run",
"lint": "eslint . --config eslint.config.mjs --cache",

View file

@ -1,5 +1,5 @@
<p align="center">
<img width="250" src="https://git.ayo.run/ayo/mcfly/raw/branch/main/assets/mcfly-logo-sm.png" alt="McFly Logo" />
<img width="250" src="https://git.sr.ht/~ayoayco/mcfly/blob/main/assets/mcfly-logo-sm.png" alt="rRick & Morty cartoon" />
</p>
<h1 align="center">McFly</h1>

View file

@ -1,6 +1,6 @@
{
"name": "@mcflyjs/config",
"version": "0.3.0-alpha",
"version": "0.2.9",
"description": "Nitro configuration for McFly apps",
"type": "module",
"main": "./dist/index.js",
@ -9,7 +9,8 @@
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./define-config": "./dist/define-config.js"
"./define-mcfly-config": "./dist/define-mcfly-config.js",
"./nitro-config": "./dist/nitro-config.js"
},
"scripts": {
"build": "tsc --erasableSyntaxOnly",
@ -19,7 +20,7 @@
},
"repository": {
"type": "git",
"url": "https://git.ayo.run/ayo/mcfly",
"url": "https://git.sr.ht/~ayoayco/mcfly",
"directory": "packages/config"
},
"author": "Ayo Ayco",
@ -31,5 +32,8 @@
"dependencies": {
"h3": "^1.15.1",
"web-component-base": "^4.0.0"
},
"devDependencies": {
"nitropack": "~2.11.7"
}
}

View file

@ -1,6 +1,8 @@
import type { NitroConfig } from 'nitropack'
export type McFlyConfig = {
server: McFlyServer
components?: 'js' | 'lit'
components: 'js' | 'lit'
nitro?: NitroConfig
plugins?: McFlyPlugin[]
}
@ -9,7 +11,7 @@ export type McFlyConfig = {
* @param {McFlyConfig} config
* @returns {function(): McFlyConfig}e
*/
export function defineConfig(config: McFlyConfig) {
export function defineMcFlyConfig(config: McFlyConfig) {
return () => config
}
@ -17,5 +19,3 @@ export function defineConfig(config: McFlyConfig) {
* TODO: finalize Plugin type
*/
export type McFlyPlugin = {}
export type McFlyServer = any

View file

@ -1 +1 @@
export { type McFlyConfig, defineConfig } from './define-config.js'
export { type McFlyConfig, defineMcFlyConfig } from './define-mcfly-config.js'

View file

@ -5,7 +5,6 @@
"allowJs": true,
"emitDeclarationOnly": false,
"declarationDir": "./dist",
"outDir": "./dist",
"rootDir": "./src"
"outDir": "./dist"
}
}

View file

@ -1,5 +1,5 @@
<p align="center">
<img width="250" src="https://git.ayo.run/ayo/mcfly/raw/branch/main/assets/mcfly-logo-sm.png" alt="McFly Logo" />
<img width="250" src="https://git.sr.ht/~ayoayco/mcfly/blob/main/assets/mcfly-logo-sm.png" alt="rRick & Morty cartoon" />
</p>
<h1 align="center">McFly</h1>

View file

@ -1,18 +1,19 @@
{
"name": "@mcflyjs/core",
"version": "0.9.0-alpha",
"version": "0.8.8",
"description": "McFly core package",
"type": "module",
"main": "./dist/index.js",
"main": "./dist/cli/index.js",
"bin": {
"mcfly": "./dist/index.js"
"mcfly": "./dist/cli/index.js"
},
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
"types": "./dist/cli/index.d.ts",
"default": "./dist/cli/index.js"
},
"./runtime": "./dist/runtime/index.js",
"./cli": "./dist/cli/index.js",
"./package.json": "./package.json"
},
"files": [
@ -26,7 +27,7 @@
},
"repository": {
"type": "git",
"url": "https://git.ayo.run/ayo/mcfly",
"url": "https://git.sr.ht/~ayoayco/mcfly",
"directory": "packages/core"
},
"author": "Ayo Ayco",
@ -42,6 +43,7 @@
"devalue": "^5.1.1",
"esprima": "^4.0.1",
"h3": "^1.15.1",
"nitropack": "^2.11.7",
"pathe": "^2.0.3",
"ultrahtml": "^1.5.3"
},

View file

@ -3,8 +3,15 @@
import { consola } from 'consola'
import { defineCommand, type ParsedArgs } from 'citty'
import { dirname, resolve } from 'pathe'
import {
build,
copyPublicAssets,
createNitro,
prepare,
prerender,
} from 'nitropack'
import { fileURLToPath } from 'node:url'
import { getMcFlyConfig } from '../get-config.js'
import { getMcFlyConfig, getNitroConfig } from '../../get-config.js'
async function _build(args: ParsedArgs) {
consola.start('Building project...')
@ -14,11 +21,33 @@ async function _build(args: ParsedArgs) {
const rootDir = resolve(dir)
const { mcflyConfig, configFile } = await getMcFlyConfig()
const nitroConfig = await getNitroConfig(mcflyConfig)
const nitro = await createNitro({
rootDir,
dev: false,
...nitroConfig,
minify: args.minify ?? nitroConfig.minify,
preset: args.preset ?? nitroConfig.preset,
})
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
consola.info('dir', __dirname)
nitro.options.handlers.push({
middleware: true,
handler: resolve(__dirname, '../../route-middleware.js'),
})
nitro.options.runtimeConfig.appConfigFile = configFile
await prepare(nitro)
await copyPublicAssets(nitro)
await prerender(nitro)
await build(nitro)
await nitro.close()
} catch (err) {
consola.error(err)
}

View file

@ -3,7 +3,8 @@
import { consola } from 'consola'
import { defineCommand, type ParsedArgs } from 'citty'
import { resolve } from 'pathe'
import { getMcFlyConfig } from '../get-config.js'
import { createNitro, writeTypes } from 'nitropack'
import { getMcFlyConfig, getNitroConfig } from '../../get-config.js'
async function prepare(args: ParsedArgs) {
consola.start('Preparing McFly workspace...')
@ -15,8 +16,10 @@ async function prepare(args: ParsedArgs) {
const dir: string = args.dir?.toString() || args._dir?.toString() || '.'
const rootDir = resolve(dir)
const { mcflyConfig } = await getMcFlyConfig()
const nitroConfig = await getNitroConfig(mcflyConfig)
const nitro = await createNitro({ rootDir, ...nitroConfig })
consola.info({ mcflyConfig, rootDir })
await writeTypes(nitro)
} catch (e) {
consola.error(e)
err = e

View file

@ -0,0 +1,129 @@
#!/usr/bin/env node
import { consola } from 'consola'
import { colorize } from 'consola/utils'
import { defineCommand, type ParsedArgs } from 'citty'
import { createRequire } from 'node:module'
import {
type Nitro,
build,
createDevServer,
createNitro,
prepare,
prerender,
} from 'nitropack'
import { resolve } from 'pathe'
import { fileURLToPath } from 'node:url'
import { dirname } from 'pathe'
import { getMcFlyConfig, getNitroConfig } from '../../get-config.js'
const hmrKeyRe = /^runtimeConfig\.|routeRules\./
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
async function printInfo() {
try {
const _require = createRequire(import.meta.url)
const mcflyPkg = await _require('@mcflyjs/core/package.json')
const mcflyPkgVersion = `McFly ${colorize('bold', mcflyPkg.version)}`
const nitroPkg = await _require('nitropack/package.json')
const nitroPkgVersion = `Nitro ${nitroPkg.version}`
consola.log(
`${colorize('blue', mcflyPkgVersion)} ${colorize('dim', nitroPkgVersion)}`
)
} catch (e) {
consola.error(e)
}
}
async function serve(args: ParsedArgs) {
try {
// TODO: check for dir type (should be string)
const dir = args.dir?.toString() || args._dir?.toString()
const rootDir: string = resolve(dir || '.')
let nitro: Nitro
const reload = async () => {
// close existing nitro
if (nitro) {
consola.info('Restarting dev server...')
if ('unwatch' in nitro.options._c12) {
await nitro.options._c12.unwatch()
}
await nitro.close()
}
const { mcflyConfig, configFile } = await getMcFlyConfig()
const nitroConfig = await getNitroConfig(mcflyConfig)
// create new nitro
nitro = await createNitro(
{
rootDir,
dev: true,
preset: 'nitro-dev',
_cli: { command: 'dev' },
...nitroConfig,
},
{
watch: true,
c12: {
async onUpdate({ getDiff, newConfig }: unknown) {
const diff = getDiff()
if (diff.length === 0) {
return // No changes
}
consola.info(
'Nitro config updated:\n' +
diff
.map((entry: unknown) => ` ${entry?.toString()}`)
.join('\n')
)
// TODO: get types for c12 config & remove unknown
// @ts-ignore
await (diff.every((e: unknown) => hmrKeyRe.test(e.key))
? nitro.updateConfig(newConfig.config || {}) // Hot reload
: reload()) // Full reload
},
},
}
)
nitro.hooks.hookOnce('restart', reload)
nitro.options.runtimeConfig.appConfigFile = configFile
nitro.options.handlers.push({
middleware: true,
handler: resolve(__dirname, '../../route-middleware.js'),
})
const server = createDevServer(nitro)
// const listenOptions = parseArgs(args)
await server.listen(1234)
await prepare(nitro)
await prerender(nitro)
await build(nitro)
}
await reload()
} catch (e) {
consola.error(e)
}
}
export default defineCommand({
meta: {
name: 'serve',
description: 'Runs the dev server.',
},
async run({ args }) {
await printInfo()
await serve(args)
},
})
export const exportedForTest = {
serve,
printInfo,
}

View file

@ -1,18 +1,6 @@
#!/usr/bin/env node
import { defineCommand, runMain, type ArgsDef, type CommandDef } from 'citty'
export type Logger = {
log: Function
error: Function
}
export type ServerConfig = {
rootDir: string
apiDir: string
port: number
logger: Logger
}
const main: CommandDef<ArgsDef> = defineCommand({
meta: {
name: 'mcfly',

View file

@ -1,67 +0,0 @@
#!/usr/bin/env node
import { consola } from 'consola'
import { colorize } from 'consola/utils'
import { defineCommand, type ParsedArgs } from 'citty'
import { createRequire } from 'node:module'
import { resolve } from 'pathe'
// import { fileURLToPath } from 'node:url'
// import { dirname } from 'pathe'
import { getMcFlyConfig } from '../get-config.js'
// const __filename = fileURLToPath(import.meta.url)
// const __dirname = dirname(__filename)
async function printInfo() {
try {
const _require = createRequire(import.meta.url)
const mcflyPkg = await _require('@mcflyjs/core/package.json')
const mcflyPkgVersion = `McFly ${colorize('bold', mcflyPkg.version)}`
consola.log(`${colorize('blue', mcflyPkgVersion)}`)
} catch (e) {
consola.error(e)
}
}
async function serve(args: ParsedArgs) {
try {
// TODO: check for dir type (should be string)
const dir = args.dir?.toString() || args._dir?.toString()
const rootDir: string = resolve(dir || '.')
const { mcflyConfig } = await getMcFlyConfig()
/**
* TODO: config
* - separate `start` & `dev` commands
* - srcDir, apiDir ?
* - autoLoad config
* - fastify config
*/
if (mcflyConfig.server)
mcflyConfig.server.serve({
rootDir: rootDir + '/src',
apiDir: '/api',
logger: consola,
})
else consola.error('[McFly]: `server` configuration required')
} catch (e) {
consola.error(e)
}
}
export default defineCommand({
meta: {
name: 'serve',
description: 'Runs the dev server.',
},
async run({ args }) {
await printInfo()
await serve(args)
},
})
export const exportedForTest = {
serve,
printInfo,
}

View file

@ -1,4 +1,27 @@
import { loadConfig } from 'c12'
import { mcflyNitroConfig } from './mcfly-nitro-config.js'
/**
* @typedef {import('nitropack').NitroConfig} NitroConfig
*/
/**
* Create a valid Nitro configuration given a McFly config object
* @returns {Promise<NitroConfig>}
*/
export async function getNitroConfig(mcflyConfig = {}) {
const { config: nitroConfig } = await loadConfig({ name: 'nitro' })
return {
// nitro config in mcfly config
...mcflyConfig.nitro,
// nitro config from nitro config
...(nitroConfig ?? {}),
// McFly standard nitro config
...mcflyNitroConfig,
}
}
export async function getMcFlyConfig() {
const { config: mcflyConfig, configFile } = await loadConfig({

View file

@ -0,0 +1,35 @@
import { type NitroConfig } from 'nitropack'
/**
* @typedef {import('nitropack').NitroConfig} NitroConfig
* @type {NitroConfig}
*/
export const mcflyNitroConfig: NitroConfig = {
framework: {
name: 'McFly',
},
compatibilityDate: '2024-12-08',
srcDir: 'src',
apiDir: 'api',
devServer: {
watch: ['./pages', './components', './api'],
},
serverAssets: [
{
baseName: 'pages',
dir: './pages',
},
{
baseName: 'components',
dir: './components',
},
],
imports: {
presets: [
{
from: 'web-component-base',
imports: ['WebComponent', 'html', 'attachEffect'],
},
],
},
}

View file

@ -0,0 +1,161 @@
import { eventHandler } from 'h3'
import { useStorage } from 'nitropack/runtime'
import { createHooks } from 'hookable'
import { consola } from 'consola'
import { colorize } from 'consola/utils'
import { useRuntimeConfig } from 'nitropack/runtime'
import { dirname, relative } from 'pathe'
import { fileURLToPath } from 'node:url'
import {
hooks as mcflyHooks,
defaultMcflyConfig,
evaluateServerScripts,
injectHtmlFragments,
injectCustomElements,
} from '@mcflyjs/core/runtime' // important to import from installed node_module because this script is passed to another context
/**
* @typedef {import('../config').McFlyConfig} Config
* @typedef {import('unstorage').Storage} Storage
* @typedef {import('unstorage').StorageValue} StorageValue
* @typedef {import('h3').EventHandler} EventHandler
*/
/**
* McFly middleware event handler
*/
export default eventHandler(async (event) => {
const timeStart = performance.now()
const hooks = createHooks()
Object.keys(mcflyHooks).forEach((hookName) => hooks.addHooks(hookName))
const { path } = event
const storage = useStorage()
const { appConfigFile } = useRuntimeConfig()
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
let relativePath = relative(__dirname, appConfigFile)
let config
// TODO: this still doesn't work on Netlify
try {
const { default: configFn } = await import(relativePath)
config = configFn()
} catch (err) {
consola.error(err)
}
// if not page, don't render
if (event.path.startsWith('/api')) {
return
}
if (!config || Object.keys(config).length === 0) {
config = defaultMcflyConfig
consola.warn(
`[WARN]: McFly configuration not found, using defaults...`,
defaultMcflyConfig
)
}
const plugins = config.plugins ?? []
plugins.forEach((plugin) => {
const pluginHooks = Object.keys(plugin)
pluginHooks.forEach((pluginHook) => {
hooks.hook(pluginHook, plugin[pluginHook])
})
})
const { components: componentType } = config
let html = await getHtml(path, storage)
if (html) {
const transforms = [
{
fn: evaluateServerScripts,
args: [event],
hook: mcflyHooks.serverScriptsEvaluated,
},
{
fn: injectHtmlFragments,
args: [storage],
hook: mcflyHooks.fragmentsInjected,
},
{
fn: injectCustomElements,
args: [componentType, storage],
hook: mcflyHooks.customElementsInjected,
},
]
if (!!componentType && !!html) {
for (const transform of transforms) {
html = await transform.fn(html.toString(), ...transform.args)
// call hook
if (transform.hook) {
// not sure if we want to await, for now it makes the outcome predictable
await hooks.callHook(transform.hook)
}
}
} else {
consola.error('[ERR]: Failed to insert registry', {
componentType: !componentType ? 'missing' : 'okay',
html: !html ? 'missing' : 'okay',
})
}
}
if (html) {
await hooks.callHook(mcflyHooks.pageRendered)
}
const timeEnd = performance.now()
consola.info(
colorize('green', event.path),
'rendered in',
Math.round(timeEnd - timeStart),
'ms'
)
return (
html ??
new Response(
'😱 ERROR 404: Not found. You can put a 404.html on the ./src/pages directory to customize this error page.',
{ status: 404 }
)
)
})
/**
* Gets the storage path for a file
* @param {string} filename
* @returns {string}
*/
function getPath(filename) {
return `assets:pages${filename}`
}
function getPurePath(path) {
return path.split('?')[0]
}
/**
* Gets the correct HTML depending on the path requested
* @param {string} path
* @param {Storage} storage
* @returns {Promise<StorageValue>}
*/
async function getHtml(path, storage) {
const purePath = getPurePath(path)
const rawPath =
purePath[purePath.length - 1] === '/' ? purePath.slice(0, -1) : purePath
const filename = rawPath === '' ? '/index.html' : `${rawPath}.html`
const fallback = getPath(rawPath + '/index.html')
const filePath = getPath(filename)
let html = await storage.getItem(filePath)
if (!html) html = await storage.getItem(fallback)
if (!html) html = await storage.getItem(getPath('/404.html'))
return html
}

View file

@ -4,3 +4,4 @@ export { getFiles } from './get-files.js'
export { hooks } from './hooks.mjs'
export { injectCustomElements } from './inject-elements.js'
export { injectHtmlFragments } from './inject-fragments.mjs'
export { mcflyNitroConfig as nitroConfig } from '../mcfly-nitro-config.js'

View file

@ -1,7 +1,7 @@
import type { ParsedArgs } from 'citty'
import consola from 'consola'
import { expect, it, vi } from 'vitest'
import { exportedForTest } from '../src/commands/build'
import { exportedForTest } from '../src/cli/commands/build.js'
const build = exportedForTest.build

View file

@ -1,6 +1,6 @@
import { consola } from 'consola'
import { it, expect, vi } from 'vitest'
import { exportedForTest } from '../src/commands/prepare'
import { exportedForTest } from '../src/cli/commands/prepare.js'
const prepare = exportedForTest.prepare
const mocks = vi.hoisted(() => {
@ -9,6 +9,12 @@ const mocks = vi.hoisted(() => {
}
})
vi.mock('nitropack', () => {
return {
createNitro: mocks.createNitro,
}
})
it('start prepare script', () => {
const spy = vi.spyOn(consola, 'start')
@ -17,6 +23,14 @@ it('start prepare script', () => {
expect(spy).toHaveBeenCalled()
})
it.skip('execute nitropack prepare', () => {
const successSpy = vi.spyOn(consola, 'success')
prepare({ dir: 'fakeDir', _: [] })
expect(successSpy).toHaveBeenCalled()
})
it.skip('catch error', () => {
const dir = 'fake-dir'
const errSpy = vi.spyOn(consola, 'error')

View file

@ -0,0 +1,12 @@
# Create Component
```
npm create @mcflyjs/component@latest
```
Create a new web component powered by [webcomponent.io](https://webcomponent.io)
---
_Just keep building._<br>
_A project by [Ayo](https://ayo.ayco.io)_

View file

@ -0,0 +1,35 @@
{
"name": "@mcflyjs/create-component",
"version": "0.0.1",
"description": "Create a new web component",
"type": "module",
"bin": {
"create-component": "./dist/index.js"
},
"main": "./dist/index.js",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"scripts": {
"build": "tsc --erasableSyntaxOnly",
"dev": "npx jiti ./src/index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://git.ayo.run/ayo/mcfly",
"directory": "packages/create-component"
},
"author": "Ayo Ayco",
"license": "MIT",
"dependencies": {
"consola": "^3.4.2",
"giget": "^3.2.0"
},
"devDependencies": {
"@types/node": "^25.6.0"
}
}

View file

@ -0,0 +1,48 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
dependencies:
consola:
specifier: ^3.4.2
version: 3.4.2
giget:
specifier: ^3.2.0
version: 3.2.0
devDependencies:
'@types/node':
specifier: ^25.6.0
version: 25.6.2
packages:
'@types/node@25.6.2':
resolution: {integrity: sha512-sokuT28dxf9JT5Kady1fsXOvI4HVpjZa95NKT5y9PNTIrs2AsobR4GFAA90ZG8M+nxVRLysCXsVj6eGC7Vbrlw==}
consola@3.4.2:
resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}
engines: {node: ^14.18.0 || >=16.10.0}
giget@3.2.0:
resolution: {integrity: sha512-GvHTWcykIR/fP8cj8dMpuMMkvaeJfPvYnhq0oW+chSeIr+ldX21ifU2Ms6KBoyKZQZmVaUAAhQ2EZ68KJF8a7A==}
hasBin: true
undici-types@7.19.2:
resolution: {integrity: sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==}
snapshots:
'@types/node@25.6.2':
dependencies:
undici-types: 7.19.2
consola@3.4.2: {}
giget@3.2.0: {}
undici-types@7.19.2: {}

View file

@ -0,0 +1,197 @@
#!/usr/bin/env node
import { consola } from 'consola'
import { colorize } from 'consola/utils'
import { downloadTemplate } from 'giget'
import { spawnSync } from 'node:child_process'
import * as path from 'node:path'
const [, , directoryArg] = process.argv
type PromptAction = {
prompt: string
info?: string
startMessage: string
command: string
subCommand: string
error: string
}
/**
* Create Web Component
*/
async function create() {
const defaultDirectory = 'hello-world'
consola.box(`Hello! Let's build a new ${colorize('bold', 'Web Component')}!`)
let directory = directoryArg
if (!directory) {
directory =
(await consola.prompt('Give your new project a name:', {
placeholder: defaultDirectory,
})) ?? defaultDirectory
} else {
consola.success(`Using ${directory} as name.`)
}
if (typeof directory !== 'string') {
return
}
directory = getSafeDirectory(directory)
const hasErrors = await downloadTemplateToDirectory(directory)
if (!hasErrors) {
const prompts: PromptAction[] = [
{
prompt: `Would you like to install the dependencies to ${colorize(
'bold',
directory
)}?`,
info: 'This might take some time depending on your connectivity.',
startMessage: 'Installing dependencies using npm...',
command: `npm`,
subCommand: 'install',
error: `Install dependencies later with ${colorize(
'yellow',
'npm install'
)}`,
},
{
prompt: 'Would you like to initialize your git repository?',
startMessage: 'Initializing git repository...',
command: `git`,
subCommand: 'init',
error: `Initialize git repository later with ${colorize(
'yellow',
'git init'
)}`,
},
]
const intentions = await askPrompts(prompts, directory)
if (!!intentions && intentions.length > 0)
showResults(directory, intentions[0])
}
}
/**
* Returns string that is safe for commands
* @param {string} directory
* @returns string
*/
function getSafeDirectory(directory: string): string {
const { platform } = process
const locale = path[platform === `win32` ? `win32` : `posix`]
const localePath = directory.split(path.sep).join(locale.sep)
return path.normalize(localePath)
}
/**
* Tries to download the template to the directory and returns a Promise whether the operation resulted to errors
* @param {string} directory
* @returns Promise<boolean> hasErrors
*/
async function downloadTemplateToDirectory(
directory: string
): Promise<boolean> {
let hasErrors = false
try {
consola.start(
`Copying template to ${colorize('bold', getSafeDirectory(directory))}...`
)
await downloadTemplate('github:ayo-run/web-component', {
dir: directory,
})
} catch (_ㆆ) {
if (_ㆆ instanceof Error) {
consola.error(_ㆆ.message)
} else {
consola.error(_ㆆ)
}
consola.info('Try a different name.\n')
hasErrors = true
}
return hasErrors
}
/**
* Iterate over an array of prompts and ask for user intention
* @param {Array<PromptAction>} prompts
* @param {string} cwd
* @returns Promise<Array<boolean> | undefined>
*/
async function askPrompts(
prompts: PromptAction[],
cwd: string
): Promise<boolean[] | undefined> {
const results: boolean[] = []
for (const p of prompts) {
const userIntends = await consola.prompt(p.prompt, {
type: 'confirm',
})
if (typeof userIntends !== 'boolean') {
return
}
if (userIntends) {
p.info && consola.info(p.info)
consola.start(p.startMessage)
try {
spawnSync(p.command, [p.subCommand], {
cwd,
shell: true,
timeout: 100_000,
stdio: 'inherit',
})
consola.success('Done!')
} catch (_ㆆ) {
if (_ㆆ instanceof Error) {
consola.error(_ㆆ.message)
} else {
consola.error(_ㆆ)
}
consola.info(p.error + '\n')
}
}
results.push(userIntends)
}
return results
}
/**
* Displays the success result string based on directory and choices
* @param {string} directory
* @param {boolean} installDeps
*/
function showResults(directory: string, installDeps: boolean) {
let nextActions = [
`Go to your project by running ${colorize('yellow', `cd ${directory}`)}`,
]
if (!installDeps) {
nextActions.push(
`Install the dependencies with ${colorize('yellow', 'npm install')}`
)
}
nextActions = nextActions.concat([
`Start the dev server with ${colorize('yellow', 'npm start')}`,
])
const result = `🎉 Your new ${colorize(
'bold',
'Web Commponent'
)} app is ready: ${directory}\n\nNext actions: ${nextActions
.map((action, index) => `\n${++index}. ${action}`)
.join('')}`
consola.box(result)
}
create()

View file

@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src"],
"compilerOptions": {
"allowJs": true,
"emitDeclarationOnly": false,
"declarationDir": "./dist",
"outDir": "./dist"
}
}

View file

@ -1,5 +1,5 @@
<p align="center">
<img width="250" src="https://git.ayo.run/ayo/mcfly/raw/branch/main/assets/mcfly-logo-sm.png" alt="McFly Logo" />
<img width="250" src="https://git.sr.ht/~ayoayco/mcfly/blob/main/assets/mcfly-logo-sm.png" alt="rRick & Morty cartoon" />
</p>
<h1 align="center">Create McFly</h1>

View file

@ -1,25 +1,27 @@
{
"name": "create-mcfly",
"version": "0.4.8",
"version": "0.4.7",
"description": "Create a new McFly app",
"type": "module",
"bin": {
"create-mcfly": "./index.js"
"create-mcfly": "./dist/index.js"
},
"main": "./index.js",
"main": "./dist/index.js",
"exports": {
".": {
"default": "./index.js"
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"scripts": {
"build": "tsc --erasableSyntaxOnly",
"version": "npm version",
"publish": "npm publish",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://git.ayo.run/ayo/mcfly",
"url": "https://git.sr.ht/~ayoayco/mcfly",
"directory": "packages/create-mcfly"
},
"author": "Ayo Ayco",

View file

@ -4,18 +4,18 @@ import { consola } from 'consola'
import { colorize } from 'consola/utils'
import { downloadTemplate } from 'giget'
import { spawnSync } from 'node:child_process'
import path from 'node:path'
import * as path from 'node:path'
const [, , directoryArg] = process.argv
/**
* @typedef {Object} PromptAction
* @property {string} prompt - The prompt text to display
* @property {string} [info] - Additional information about the prompt
* @property {string} startMessage - Message to show when starting the action
* @property {string} command - The command to execute
* @property {string} subCommand - The subcommand to execute
* @property {string} error - Error message to display on failure
*/
type PromptAction = {
prompt: string
info?: string
startMessage: string
command: string
subCommand: string
error: string
}
/**
* Create McFly App
@ -42,10 +42,7 @@ async function create() {
const hasErrors = await downloadTemplateToDirectory(directory)
if (!hasErrors) {
/**
* @type {Array<PromptAction>}
*/
const prompts = [
const prompts: PromptAction[] = [
{
prompt: `Would you like to install the dependencies to ${colorize(
'bold',
@ -83,7 +80,7 @@ async function create() {
* @param {string} directory
* @returns string
*/
function getSafeDirectory(directory) {
function getSafeDirectory(directory: string): string {
const { platform } = process
const locale = path[platform === `win32` ? `win32` : `posix`]
const localePath = directory.split(path.sep).join(locale.sep)
@ -95,14 +92,16 @@ function getSafeDirectory(directory) {
* @param {string} directory
* @returns Promise<boolean> hasErrors
*/
async function downloadTemplateToDirectory(directory) {
async function downloadTemplateToDirectory(
directory: string
): Promise<boolean> {
let hasErrors = false
try {
consola.start(
`Copying template to ${colorize('bold', getSafeDirectory(directory))}...`
)
await downloadTemplate('github:ayo-run/mcfly/templates/basic', {
await downloadTemplate('sourcehut:ayoayco/mcfly/templates/basic', {
dir: directory,
})
} catch (_ㆆ) {
@ -124,11 +123,11 @@ async function downloadTemplateToDirectory(directory) {
* @param {string} cwd
* @returns Promise<Array<boolean> | undefined>
*/
async function askPrompts(prompts, cwd) {
/**
* @type {Array<boolean>}
*/
const results = []
async function askPrompts(
prompts: PromptAction[],
cwd: string
): Promise<boolean[] | undefined> {
const results: boolean[] = []
for (const p of prompts) {
const userIntends = await consola.prompt(p.prompt, {
@ -170,7 +169,7 @@ async function askPrompts(prompts, cwd) {
* @param {string} directory
* @param {boolean} installDeps
*/
function showResults(directory, installDeps) {
function showResults(directory: string, installDeps: boolean) {
let nextActions = [
`Go to your project by running ${colorize('yellow', `cd ${directory}`)}`,
]
@ -190,7 +189,7 @@ function showResults(directory, installDeps) {
'bold',
'McFly'
)} app is ready: ${directory}\n\nNext actions: ${nextActions
.map((action, index) => `\n${index}. ${action}`)
.map((action, index) => `\n${++index}. ${action}`)
.join('')}`
consola.box(result)

View file

@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src"],
"compilerOptions": {
"allowJs": true,
"emitDeclarationOnly": false,
"declarationDir": "./dist",
"outDir": "./dist"
}
}

View file

@ -1,72 +0,0 @@
<p align="center">
<img width="250" src="https://git.ayo.run/ayo/mcfly/raw/branch/main/assets/mcfly-logo-sm.png" alt="McFly Logo" />
</p>
<h1 align="center">McFly Fastify Adapter</h1>
Use fastify as a server framework in McFly
```
npm create mcfly@latest
```
<p align="center"><strong>McFly</strong> is a no-framework framework<br />that assists in building on the Web</p>
<p align="center">
<img src="https://img.shields.io/badge/from-the_future-blue?style=flat" />
<img src="https://img.shields.io/badge/status-legit-purple?style=flat" />
<a href="https://mc-fly.vercel.app/demo" target="_blank"><img src="https://img.shields.io/badge/see-the_demo_↗-blue?style=flat&colorB=28CF8D" /></a>
</p>
## Features
The time has come for vanilla Web tech. 🎉
✅ Create web apps with vanilla custom elements<br>
✅ Write real .HTML files<br>
✅ Have no frameworks or reactivity libraries on the browser<br>
✅ Use server-side rendering<br>
✅ Deploy anywhere<br>
## Special directories
**1. `./src/pages/`**
- file-based routing for `.html` files
- directly use custom elements & static fragments (no imports or registry maintenance needed)
- use `<script server:setup>` to define logic that runs on the server, which then gets stripped away
**2. `./src/components/`**
- custom element constructor files (only `.js` files for now)
- all components are automatically registered using their file names; a `hello-world.js` component can be used as `<hello-world>`
- static `.html` fragments; a `my-header.html` fragment can be directly used as `<my-header>`
**3. `./src/api/`**
- file-based routing for REST API endpoints
- e.g., `./src/api/users.ts` can be accessed via `http://<domain>/api/users`
- TypeScript or JavaScript welcome!
## McFly config
To tell McFly you want to use components, pass the mode (only `"js"` for now) to the `components` prop mcfly.config.ts
```js
import defineConfig from './packages/define-config'
export default defineConfig({
components: 'js',
})
```
## More info
This framework is a result of [an exploration](https://social.ayco.io/@ayo/111195315785886977) for using [**Nitro**](https://nitro.unjs.io) and vanilla JS custom elements using a minimal [**Web Component Base**](https://WebComponent.io) class.
**Nitro** is the same production-grade web server powering [**Nuxt**](https://nuxt.com/)
---
_Just keep building_<br />
_A project by [Ayo](https://ayco.io)_

View file

@ -1,7 +0,0 @@
import serve from './serve'
export default () => {
return {
serve,
}
}

View file

@ -1,19 +0,0 @@
{
"name": "@mcflyjs/fastify",
"version": "0.1.0",
"type": "module",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@fastify/autoload": "6.3.1",
"fastify": "5.8.5"
},
"devDependencies": {
"@mcflyjs/core": "workspace:*"
}
}

View file

@ -1,29 +0,0 @@
import Fastify from 'fastify'
import AutoLoad from '@fastify/autoload'
import path from 'node:path'
/**
* @typedef {import('@mcflyjs/core').ServerConfig} ServerConfig
*/
/**
* @param {ServerConfig} param
*/
export default ({ rootDir, apiDir, logger, port }) => {
const server = Fastify()
const portNumber = port ?? 3000
server.register(AutoLoad, {
dir: path.join(rootDir, apiDir),
options: {
prefix: apiDir,
},
})
server
.listen({ port: portNumber })
.then(() => {
logger.log(`API now serving at http://localhost:${portNumber}${apiDir}`)
})
.catch((err) => logger.error(err))
}

File diff suppressed because it is too large Load diff

View file

@ -1,16 +1,11 @@
packages:
- 'packages/**'
- 'templates/**'
- 'site'
- 'demo'
- "packages/**"
- "templates/**"
- "site/**"
allowBuilds:
'@parcel/watcher': false
esbuild: true
netlify-cli: false
sharp: false
unix-dgram: false
web-component-base: true
minimumReleaseAgeExclude:
- '@mcflyjs/config@0.3.0-alpha'
- '@mcflyjs/core@0.9.0-alpha'
- '@mcflyjs/fastify@0.1.0'
'@parcel/watcher': set this to true or false
esbuild: set this to true or false
netlify-cli: set this to true or false
sharp: set this to true or false
unix-dgram: set this to true or false
web-component-base: set this to true or false

View file

@ -1,5 +1,5 @@
<p align="center">
<img width="250" src="https://git.ayo.run/ayo/mcfly/raw/branch/main/assets/mcfly-logo-sm.png" alt="McFly Logo" />
<img width="250" src="https://git.sr.ht/~ayoayco/mcfly/blob/main/assets/mcfly-logo-sm.png" alt="rRick & Morty cartoon" />
</p>
<h1 align="center">McFly Docs</h1>

View file

@ -1,28 +1,27 @@
// @ts-check
import { defineConfig } from '@mcflyjs/config'
import { defineMcFlyConfig } from '@mcflyjs/config'
// import testPlugin from './test-plugin.mjs'
export default defineConfig({
server: {},
export default defineMcFlyConfig({
components: 'js',
// plugins: [testPlugin()],
// nitro: {
// preset: 'netlify',
// devServer: {
// watch: ['../packages'],
// },
// routeRules: {
// '/chat': {
// redirect: {
// to: 'https://matrix.to/#/#mcfly:matrix.org',
// statusCode: 302,
// },
// },
// },
// compressPublicAssets: {
// gzip: true,
// brotli: true,
// },
// compatibilityDate: '2024-12-08',
// },
nitro: {
preset: 'netlify',
devServer: {
watch: ['../packages'],
},
routeRules: {
'/chat': {
redirect: {
to: 'https://matrix.to/#/#mcfly:matrix.org',
statusCode: 302,
},
},
},
compressPublicAssets: {
gzip: true,
brotli: true,
},
compatibilityDate: '2024-12-08',
},
})

View file

@ -6,7 +6,7 @@
"main": "index.js",
"repository": {
"type": "git",
"url": "https://git.ayo.run/ayo/mcfly",
"url": "https://git.sr.ht/~ayoayco/mcfly",
"directory": "app"
},
"author": "Ayo Ayco",

View file

@ -30,7 +30,7 @@
<warning-block
><span>This page is in-progress. See the
<a
href="https://git.ayo.run/ayo/mcfly/tree/main/item/site/src/pages/demo.html"
href="https://git.sr.ht/~ayoayco/mcfly/tree/main/item/site/src/pages/demo.html"
>source code</a
>.</span></warning-block
>

View file

@ -1,6 +0,0 @@
// @ts-check
import { defineMcFlyConfig } from '@mcflyjs/config'
export default defineMcFlyConfig({
components: 'js',
})

View file

@ -1,16 +0,0 @@
{
"name": "basic-legacy-template",
"description": "McFly starter project",
"scripts": {
"start": "mcfly serve",
"prepare": "mcfly prepare",
"dev": "mcfly serve",
"build": "mcfly build",
"preview": "node .output/server/index.mjs",
"build:preview": "npm run build && npm run preview"
},
"dependencies": {
"@mcflyjs/config": "^0.2.9",
"@mcflyjs/core": "^0.8.8"
}
}

View file

@ -1,53 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<!--
Hello! This page is an example McFly page.
See more on https://ayco.io/sh/mcfly
-->
<my-head>
<title>McFly: Back to the Basics. Into the Future.</title>
<script server:setup>
const project = {
name: "McFly",
description: "Back to the Basics. Into the Future."
};
</script>
</my-head>
<body>
<awesome-header>
<span>{{ project.name }}</span>
<span slot="description">{{ project.description }}</span>
</awesome-header>
<main>
<h2>Welcome to {{ project.name }}</h2>
<p>Server date time: {{new Date().toLocaleString()}}</p>
<p>
Here's an interactive custom element:
<my-hello-world></my-hello-world>
</p>
<code-block language="js">
class MyHelloWorld extends WebComponent {
static props = {
myName: &quot;World&quot;,
count: 0
}
updateLabel() {
this.props.myName = `Clicked ${++this.props.count}x`;
}
get template() {
return html`
&lt;button onClick=${() => this.updateLabel()} style="cursor:pointer"&gt;
Hello ${this.props.myName}!
&lt;/button&gt;`;
}
}</code-block>
</main>
<my-footer>
<small>
Learn how to build components easily at <a href="https://WebComponent.io">WebComponent.io</a>
</small>
</my-footer>
</body>
</html>

View file

@ -1,6 +1,6 @@
import { defineConfig } from '@mcflyjs/config'
import fastify from '@mcflyjs/fastify'
// @ts-check
import { defineMcFlyConfig } from '@mcflyjs/config'
export default defineConfig({
server: fastify(),
export default defineMcFlyConfig({
components: 'js',
})

View file

@ -1,17 +1,16 @@
{
"name": "mcfly-basic",
"version": "1.0.0",
"description": "",
"main": "index.js",
"name": "basic-template",
"description": "McFly starter project",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "mcfly serve"
"start": "mcfly serve",
"prepare": "mcfly prepare",
"dev": "mcfly serve",
"build": "mcfly build",
"preview": "node .output/server/index.mjs",
"build:preview": "npm run build && npm run preview"
},
"author": "",
"license": "ISC",
"dependencies": {
"@mcflyjs/config": "^0.3.0-alpha",
"@mcflyjs/core": "^0.9.0-alpha",
"@mcflyjs/fastify": "^0.1"
"@mcflyjs/config": "^0.2.9",
"@mcflyjs/core": "^0.8.8"
}
}

View file

@ -1,29 +0,0 @@
# Routes Folder
Routes define the pathways within your application.
Fastify's structure supports the modular monolith approach, where your
application is organized into distinct, self-contained modules.
This facilitates easier scaling and future transition to a microservice architecture.
In the future you might want to independently deploy some of those.
In this folder you should define all the routes that define the endpoints
of your web application.
Each service is a [Fastify
plugin](https://fastify.dev/docs/latest/Reference/Plugins/), it is
encapsulated (it can have its own independent plugins) and it is
typically stored in a file; be careful to group your routes logically,
e.g. all `/users` routes in a `users.js` file. We have added
a `root.js` file for you with a '/' root added.
If a single file becomes too large, create a folder and add a `index.js` file there:
this file must be a Fastify plugin, and it will be loaded automatically
by the application. You can now add as many files as you want inside that folder.
In this way you can create complex routes within a single monolith,
and eventually extract them.
If you need to share functionality between routes, place that
functionality into the `plugins` folder, and share it via
[decorators](https://fastify.dev/docs/latest/Reference/Decorators/).
If you're a bit confused about using `async/await` to write routes, you would
better take a look at [Promise resolution](https://fastify.dev/docs/latest/Reference/Routes/#promise-resolution) for more details.

View file

@ -1,6 +0,0 @@
export default async (fastify) => {
fastify.get('/', async function (request, reply) {
console.log({ request, reply })
return 'This is an example'
})
}

View file

@ -1,5 +0,0 @@
export default async (fastify) => {
fastify.get('/', async function (request, reply) {
return 'This is the API Index'
})
}

View file

@ -1,6 +0,0 @@
export default async function (fastify, opts) {
fastify.get('/', async function (request, reply) {
console.log({ opts, request, reply })
return { root: true }
})
}

View file

@ -1,12 +1,53 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WORK IN PROGRESS</title>
</head>
<body>
<h1>WORK IN PROGRESS</h1>
<p>See <a href="https://ayco.io/sh/mcfly">the project repository</a> for more info.</p>
</body>
<!--
Hello! This page is an example McFly page.
See more on https://ayco.io/sh/mcfly
-->
<my-head>
<title>McFly: Back to the Basics. Into the Future.</title>
<script server:setup>
const project = {
name: "McFly",
description: "Back to the Basics. Into the Future."
};
</script>
</my-head>
<body>
<awesome-header>
<span>{{ project.name }}</span>
<span slot="description">{{ project.description }}</span>
</awesome-header>
<main>
<h2>Welcome to {{ project.name }}</h2>
<p>Server date time: {{new Date().toLocaleString()}}</p>
<p>
Here's an interactive custom element:
<my-hello-world></my-hello-world>
</p>
<code-block language="js">
class MyHelloWorld extends WebComponent {
static props = {
myName: &quot;World&quot;,
count: 0
}
updateLabel() {
this.props.myName = `Clicked ${++this.props.count}x`;
}
get template() {
return html`
&lt;button onClick=${() => this.updateLabel()} style="cursor:pointer"&gt;
Hello ${this.props.myName}!
&lt;/button&gt;`;
}
}</code-block>
</main>
<my-footer>
<small>
Learn how to build components easily at <a href="https://WebComponent.io">WebComponent.io</a>
</small>
</my-footer>
</body>
</html>

View file

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

View file

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View file

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

View file

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

View file

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 22 KiB