Skip to content

Commit 8b26218

Browse files
committed
feat: ofetch integration
1 parent 92b2ddf commit 8b26218

File tree

7 files changed

+3911
-1123
lines changed

7 files changed

+3911
-1123
lines changed

adex/package.json

+6-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
"types": "./src/ssr.d.ts",
2222
"import": "./src/ssr.js"
2323
},
24+
"./types": {
25+
"types": "./types.d.ts"
26+
},
2427
"./head": {
2528
"types": "./src/head.d.ts",
2629
"import": "./src/head.js"
@@ -61,11 +64,13 @@
6164
"hoofd": "^1.7.1",
6265
"mri": "^1.2.0",
6366
"node-stream-zip": "^1.15.0",
67+
"ofetch": "^1.4.1",
6468
"preact-render-to-string": "^6.5.5",
6569
"regexparam": "^3.0.0",
6670
"sirv": "^2.0.4",
6771
"trouter": "^4.0.0",
68-
"unifont": "^0.0.2"
72+
"unifont": "^0.0.2",
73+
"unimport": "^4.0.0"
6974
},
7075
"devDependencies": {
7176
"@preact/preset-vite": "^2.8.2",

adex/runtime/fetch.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { ofetch as _ofetch } from 'ofetch'
2+
import { env } from 'adex/env'
3+
4+
const constructBaseURL = () => {
5+
if (import.meta.server) {
6+
const origin = env.get('HOST', 'localhost')
7+
const port = env.get('PORT', '3000')
8+
return new URL(`http:${origin}${port ? `:${port}` : ''}`).toString()
9+
}
10+
return window.location.toString()
11+
}
12+
13+
const baseURL = constructBaseURL()
14+
export const $fetch = _ofetch.create({
15+
baseURL: baseURL,
16+
})

adex/src/env.js

+13-12
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
1-
const isClient = typeof window !== 'undefined'
1+
export const env = {}
22

3-
if (isClient) {
4-
throw new Error('[adex] Cannot use/import `adex/env` on the client side')
5-
}
6-
7-
export const env = {
8-
get(key, defaultValue = '') {
9-
if (isClient) return ''
3+
if (import.meta.server) {
4+
env.get = (key, defaultValue = '') => {
105
return process.env[key] ?? defaultValue
11-
},
12-
set(key, value) {
13-
if (isClient) return ''
6+
}
7+
env.set = (key, value) => {
148
return (process.env[key] = value)
15-
},
9+
}
10+
} else {
11+
env.get = (key, defaultValue = '') => {
12+
return import.meta.env[key] ?? defaultValue
13+
}
14+
env.set = (key, value) => {
15+
return (import.meta.env[key] = value)
16+
}
1617
}

adex/src/ssr.d.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ export { renderToString } from 'preact-render-to-string'
33
export { parse as pathToRegex } from 'regexparam'
44
export { use as useMiddleware } from '@barelyhuman/tiny-use'
55
export { default as sirv } from 'sirv'
6-
export { default as mri } from 'mri'
6+
export { default as mri } from 'mri'

adex/src/vite.js

+41-41
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
isFunctionIsland,
1010
readSourceFile,
1111
} from '@dumbjs/preland'
12+
import Unimport from 'unimport/unplugin'
1213
import { addImportToAST, codeFromAST } from '@dumbjs/preland/ast'
1314
import preact from '@preact/preset-vite'
1415
import { mkdirSync, readFileSync, writeFileSync } from 'fs'
@@ -37,6 +38,7 @@ export function adex({
3738
adapter: adapter = 'node',
3839
} = {}) {
3940
return [
41+
adexConfig(),
4042
preactPages({
4143
root: '/src/pages',
4244
id: '~routes',
@@ -61,15 +63,15 @@ export function adex({
6163
import { dirname, join } from 'node:path'
6264
import { fileURLToPath } from 'node:url'
6365
import { existsSync, readFileSync } from 'node:fs'
64-
import { env } from 'adex/env'
66+
import {env} from "adex/env"
6567
6668
import 'virtual:adex:font.css'
6769
import 'virtual:adex:global.css'
6870
6971
const __dirname = dirname(fileURLToPath(import.meta.url))
7072
71-
const PORT = parseInt(env.get('PORT', '3000'), 10)
72-
const HOST = env.get('HOST', 'localhost')
73+
const PORT = parseInt(env.get("PORT","3000"))
74+
const HOST = env.get("HOST","localhost")
7375
7476
const paths = {
7577
assets: join(__dirname, './assets'),
@@ -128,7 +130,6 @@ export function adex({
128130
adexServerBuilder({ islands }),
129131
!islands && adexClientBuilder(),
130132
islands && adexIslandsBuilder(),
131-
...adexGuards(),
132133
]
133134
}
134135

@@ -212,6 +213,10 @@ function adexIslandsBuilder() {
212213
await build({
213214
configFile: false,
214215
plugins: [preact()],
216+
define: {
217+
'import.meta.server': false,
218+
'import.meta.client': true,
219+
},
215220
build: {
216221
ssr: false,
217222
outDir: join(outDir, 'islands'),
@@ -346,6 +351,10 @@ function adexClientBuilder() {
346351
),
347352
preact({ prefreshEnabled: false }),
348353
],
354+
define: {
355+
'import.meta.client': true,
356+
'import.meta.server': false,
357+
},
349358
build: {
350359
outDir: 'dist/client',
351360
emptyOutDir: true,
@@ -388,8 +397,12 @@ function adexServerBuilder({ islands = false } = {}) {
388397
return {
389398
appType: 'custom',
390399
ssr: {
391-
external: ['preact', 'adex', 'preact-render-to-string'],
392-
noExternal: Object.values(adapterMap),
400+
external: ['preact', 'preact-render-to-string'],
401+
noExternal: Object.values(adapterMap).concat('adex/env'),
402+
},
403+
define: {
404+
'import.meta.server': true,
405+
'import.meta.client': false,
393406
},
394407
build: {
395408
outDir: 'dist/server',
@@ -479,45 +492,32 @@ function adexServerBuilder({ islands = false } = {}) {
479492
/**
480493
* @returns {import("vite").Plugin[]}
481494
*/
482-
function adexGuards() {
495+
function adexConfig() {
483496
return [
497+
// @ts-expect-error something wrong wrong
498+
Unimport.vite({
499+
imports: [
500+
{
501+
name: '$fetch',
502+
from: fileURLToPath(new URL('../runtime/fetch.js', import.meta.url)),
503+
},
504+
],
505+
}),
484506
{
485-
name: 'adex-guard-env',
507+
name: 'adex-config',
486508
enforce: 'pre',
487-
async transform(code, id) {
488-
// ignore usage of `process.env` in node_modules
489-
// Still risky but hard to do anything about
490-
const nodeMods = resolve(cwd, 'node_modules')
491-
if (id.startsWith(nodeMods)) return
492-
493-
// ignore usage of `process.env` in `adex/env`
494-
const envLoadId = await this.resolve('adex/env')
495-
if (id === envLoadId.id) return
496-
497-
if (code.includes('process.env')) {
498-
this.error(
499-
'Avoid using `process.env` to access environment variables and secrets. Use `adex/env` instead'
500-
)
501-
}
502-
},
503-
writeBundle() {
504-
const pagesPath = resolve(cwd, 'src/pages')
505-
const info = this.getModuleInfo('adex/env')
506-
const viteRef = this
507-
508-
function checkTree(importPath, importStack = []) {
509-
if (importPath.startsWith(pagesPath)) {
510-
throw new Error(
511-
`Cannot use/import \`adex/env\` on the client side, importerStack: ${importStack.join(' -> ')}`
512-
)
513-
}
514-
viteRef
515-
.getModuleInfo(importPath)
516-
.importers.forEach(d =>
517-
checkTree(d, [...importStack, importPath, d])
518-
)
509+
config() {
510+
return {
511+
server: {
512+
port: 3000,
513+
},
514+
define: {
515+
'import.meta.env.PORT': JSON.stringify(process.env.PORT ?? '3000'),
516+
'import.meta.env.HOST': JSON.stringify(
517+
process.env.HOST ?? 'localhost'
518+
),
519+
},
519520
}
520-
info.importers.forEach(i => checkTree(i))
521521
},
522522
},
523523
]

adex/types.d.ts

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
interface ImportMeta {
2+
readonly server: boolean
3+
readonly client: boolean
4+
}

0 commit comments

Comments
 (0)