Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: injectTypes #11551

Merged
merged 52 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from 32 commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
e074704
feat: make inline config 1st arg
florian-lefebvre Jul 25, 2024
e28c8ed
fix: run config done in sync
florian-lefebvre Jul 25, 2024
8a5c2a2
feat: start working on injectTypes
florian-lefebvre Jul 25, 2024
4fb6bbe
feat: write files
florian-lefebvre Jul 25, 2024
9f2ccea
feat: adapt core features
florian-lefebvre Jul 25, 2024
b2c14e9
feat: migrate db to injectTypes
florian-lefebvre Jul 25, 2024
04b828c
feat: special db handling
florian-lefebvre Jul 25, 2024
dc53d1a
feat: update settings instead of workarounds
florian-lefebvre Jul 26, 2024
adeeaa2
fix: create dotAstroDir
florian-lefebvre Jul 26, 2024
bf1686b
feat: refactor sync tests
florian-lefebvre Jul 26, 2024
c770927
Merge branch 'main' into feat/inject-types
florian-lefebvre Jul 26, 2024
9fe686e
fix: path
florian-lefebvre Jul 26, 2024
ef75b5a
Merge branch 'feat/inject-types' of https://github.com/withastro/astr…
florian-lefebvre Jul 26, 2024
f3f02f7
fix: paths
florian-lefebvre Jul 26, 2024
c08bff9
chore: add comments
florian-lefebvre Jul 26, 2024
fe62fe5
feat: overwrite content file if exists
florian-lefebvre Aug 5, 2024
4b89dbc
chore: remove unused db env related code
florian-lefebvre Aug 5, 2024
d7df994
feat: use dotAstroDir for settings
florian-lefebvre Aug 5, 2024
6a85ce6
chore: simplify astro env sync
florian-lefebvre Aug 5, 2024
ea1bde4
feat: use dotAstroDir for preferences
florian-lefebvre Aug 5, 2024
badc2a5
feat: handle db in integration api
florian-lefebvre Aug 5, 2024
2bee83d
chore: reorganize
florian-lefebvre Aug 5, 2024
fe82d08
feat: format
florian-lefebvre Aug 5, 2024
c474594
feat: add test
florian-lefebvre Aug 5, 2024
8d8a32e
Discard changes to examples/basics/astro.config.mjs
florian-lefebvre Aug 5, 2024
157238a
Discard changes to examples/basics/package.json
florian-lefebvre Aug 5, 2024
d590704
Discard changes to pnpm-lock.yaml
florian-lefebvre Aug 5, 2024
81578f2
chore: remove test files
florian-lefebvre Aug 5, 2024
d0838c4
feat: update examples dts
florian-lefebvre Aug 5, 2024
956d5cb
fix: dts
florian-lefebvre Aug 5, 2024
54fd383
Merge branch 'main' into feat/inject-types
florian-lefebvre Aug 5, 2024
f18ff9d
chore: changesets
florian-lefebvre Aug 5, 2024
4a64b5c
fix: indentation
florian-lefebvre Aug 5, 2024
6115c10
Apply suggestions from code review
florian-lefebvre Aug 6, 2024
b266274
Apply suggestions from code review
florian-lefebvre Aug 6, 2024
2916b1f
Merge branch 'main' into feat/inject-types
florian-lefebvre Aug 8, 2024
29bcfc3
chore: format
florian-lefebvre Aug 8, 2024
a5fbfe9
Update packages/astro/src/integrations/hooks.ts
florian-lefebvre Aug 8, 2024
082553c
Update .changeset/mean-horses-kiss.md
florian-lefebvre Aug 9, 2024
ddd5915
Merge branch 'main' into feat/inject-types
florian-lefebvre Aug 9, 2024
6602653
feat: remove formatting
florian-lefebvre Aug 9, 2024
e53f9ab
feat: handle fs errors
florian-lefebvre Aug 9, 2024
934406a
feat: remove astro:db special path handling
florian-lefebvre Aug 9, 2024
c2a3dd2
Merge branch 'main' into feat/inject-types
florian-lefebvre Aug 12, 2024
f512569
feat: add fs error
florian-lefebvre Aug 12, 2024
ca93448
Update packages/astro/src/content/types-generator.ts
florian-lefebvre Aug 12, 2024
62fb454
Merge branch 'content-layer' into feat/inject-types
florian-lefebvre Aug 12, 2024
24089e2
Update .changeset/mean-horses-kiss.md
florian-lefebvre Aug 13, 2024
7f702b0
Update errors-data.ts
florian-lefebvre Aug 13, 2024
27426b5
Update .changeset/mean-horses-kiss.md
florian-lefebvre Aug 13, 2024
8f38a9d
Update .changeset/mean-horses-kiss.md
florian-lefebvre Aug 13, 2024
c4235c3
Merge branch 'content-layer' into feat/inject-types
Princesseuh Aug 14, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/fresh-fans-study.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@astrojs/db': minor
---

Changes how typegen works
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved

The generated dts file is now at a new location:
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved

```diff
- .astro/db-types.d.ts
+ .astro/astro/db.d.ts
```

The update made to `src/env.d.ts` can be undone:

```diff
- /// <reference path="../.astro/db-types.d.ts" />
```
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
26 changes: 26 additions & 0 deletions .changeset/mean-horses-kiss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
'astro': minor
---

Adds a new `injectTypes` utility to the Integration API and refactors how typegen works
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved

Integrations can now use a new `injectTypes` utility exposed on the `astro:config:done` hook. It allows to inject types easily in the user's project. `filename` must ends with `".d.ts"` and `content` must be valid TypeScript (it will be formatted).

Under the hood, it will create a file at `/.astro/integrations/<normalized_integration_name>/<normalized_filename>.d.ts` and create references to it. `injectTypes` returns a URL to the normalized path.
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved

```js
const path = injectTypes({
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the point of it returning the path?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See what we're doing in core for content sync (ie. overriding the dts file with content updates)? I can imagine some people wanting to do this in integrations. Since we normalize the filename, people can't easily construct the path themselves so we give it to them

filename: "types.d.ts",
content: "declare module 'virtual:integration' {}"
})
console.log(path) // URL
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
```

Codegen has been refactored. As a user, you just need to update `src/env.d.ts`:
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved

```diff
- /// <reference types="astro/client" />
+ /// <reference path="../.astro/types.d.ts" />
- /// <reference path="../.astro/env.d.ts" />
- /// <reference path="../.astro/actions.d.ts" />
```
bluwy marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 1 addition & 1 deletion examples/basics/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
1 change: 0 additions & 1 deletion examples/blog/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />
2 changes: 1 addition & 1 deletion examples/framework-alpine/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/framework-lit/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/framework-multiple/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/framework-preact/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/framework-react/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/framework-solid/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/framework-svelte/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/framework-vue/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/hackernews/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/middleware/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
declare namespace App {
interface Locals {
user: {
Expand Down
2 changes: 1 addition & 1 deletion examples/minimal/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/non-html-pages/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
1 change: 0 additions & 1 deletion examples/portfolio/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />
2 changes: 1 addition & 1 deletion examples/ssr/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
1 change: 0 additions & 1 deletion examples/with-markdoc/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />
2 changes: 1 addition & 1 deletion examples/with-markdown-plugins/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/with-markdown-shiki/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/with-mdx/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/with-nanostores/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
2 changes: 1 addition & 1 deletion examples/with-tailwindcss/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
7 changes: 7 additions & 0 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2345,6 +2345,11 @@ export interface AstroAdapterFeatures {
functionPerRoute: boolean;
}

export interface InjectedType {
filename: string;
content: string;
}

export interface AstroSettings {
config: AstroConfig;
adapter: AstroAdapter | undefined;
Expand Down Expand Up @@ -2380,6 +2385,7 @@ export interface AstroSettings {
latestAstroVersion: string | undefined;
serverIslandMap: NonNullable<SSRManifest['serverIslandMap']>;
serverIslandNameMap: NonNullable<SSRManifest['serverIslandNameMap']>;
injectedTypes: Array<InjectedType>;
}

export type AsyncRendererComponentFn<U> = (
Expand Down Expand Up @@ -3081,6 +3087,7 @@ declare global {
'astro:config:done': (options: {
config: AstroConfig;
setAdapter: (adapter: AstroAdapter) => void;
injectTypes: (injectedType: InjectedType) => URL;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
'astro:server:setup': (options: {
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/actions/consts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export const VIRTUAL_MODULE_ID = 'astro:actions';
export const RESOLVED_VIRTUAL_MODULE_ID = '\0' + VIRTUAL_MODULE_ID;
export const ACTIONS_TYPES_FILE = 'actions.d.ts';
export const ACTIONS_TYPES_FILE = 'astro/actions.d.ts';
export const VIRTUAL_INTERNAL_MODULE_ID = 'astro:internal-actions';
export const RESOLVED_VIRTUAL_INTERNAL_MODULE_ID = '\0astro:internal-actions';
export const NOOP_ACTIONS = '\0noop-actions';
39 changes: 11 additions & 28 deletions packages/astro/src/actions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,6 @@ export default function astroActions({
throw error;
}

const stringifiedActionsImport = JSON.stringify(
viteID(new URL('./actions', params.config.srcDir))
);
params.updateConfig({
vite: {
plugins: [vitePluginUserActions({ settings }), vitePluginActions(fs)],
Expand All @@ -49,11 +46,18 @@ export default function astroActions({
entrypoint: 'astro/actions/runtime/middleware.js',
order: 'post',
});
},
'astro:config:done': (params) => {
const stringifiedActionsImport = JSON.stringify(
viteID(new URL('./actions', params.config.srcDir))
);
settings.injectedTypes.push({
filename: ACTIONS_TYPES_FILE,
content: `declare module "astro:actions" {
type Actions = typeof import(${stringifiedActionsImport})["server"];

await typegen({
stringifiedActionsImport,
root: params.config.root,
fs,
export const actions: Actions;
}`,
});
},
},
Expand Down Expand Up @@ -119,24 +123,3 @@ const vitePluginActions = (fs: typeof fsMod): VitePlugin => ({
return code;
},
});

async function typegen({
stringifiedActionsImport,
root,
fs,
}: {
stringifiedActionsImport: string;
root: URL;
fs: typeof fsMod;
}) {
const content = `declare module "astro:actions" {
type Actions = typeof import(${stringifiedActionsImport})["server"];

export const actions: Actions;
}`;

const dotAstroDir = new URL('.astro/', root);

await fs.promises.mkdir(dotAstroDir, { recursive: true });
await fs.promises.writeFile(new URL(ACTIONS_TYPES_FILE, dotAstroDir), content);
}
2 changes: 1 addition & 1 deletion packages/astro/src/cli/check/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export async function check(flags: Arguments) {
// For now, we run this once as usually `astro check --watch` is ran alongside `astro dev` which also calls `astro sync`.
const { default: sync } = await import('../../core/sync/index.js');
try {
await sync({ inlineConfig: flagsToAstroInlineConfig(flags) });
await sync(flagsToAstroInlineConfig(flags));
} catch (_) {
return process.exit(1);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/cli/sync/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export async function sync({ flags }: SyncOptions) {
}

try {
await _sync({ inlineConfig: flagsToAstroInlineConfig(flags), telemetry: true });
await _sync(flagsToAstroInlineConfig(flags), { telemetry: true });
return 0;
} catch (_) {
return 1;
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/content/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ export const CONTENT_FLAGS = [
PROPAGATED_ASSET_FLAG,
] as const;

export const CONTENT_TYPES_FILE = 'types.d.ts';
export const CONTENT_TYPES_FILE = 'astro/content.d.ts';
18 changes: 13 additions & 5 deletions packages/astro/src/content/types-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ async function writeContentFiles({
}

const configPathRelativeToCacheDir = normalizeConfigPath(
settings.dotAstroDir.pathname,
new URL('astro', settings.dotAstroDir).pathname,
contentPaths.config.url.pathname
);

Expand All @@ -515,8 +515,16 @@ async function writeContentFiles({
contentConfig ? `typeof import(${configPathRelativeToCacheDir})` : 'never'
);

await fs.promises.writeFile(
new URL(CONTENT_TYPES_FILE, settings.dotAstroDir),
typeTemplateContent
);
if (settings.injectedTypes.some((t) => t.filename === CONTENT_TYPES_FILE)) {
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
fs.promises.writeFile(
new URL(CONTENT_TYPES_FILE, settings.dotAstroDir),
typeTemplateContent,
'utf-8'
);
} else {
settings.injectedTypes.push({
filename: CONTENT_TYPES_FILE,
content: typeTemplateContent,
});
}
}
6 changes: 4 additions & 2 deletions packages/astro/src/core/config/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import { loadTSConfig } from './tsconfig.js';

export function createBaseSettings(config: AstroConfig): AstroSettings {
const { contentDir } = getContentPaths(config);
const preferences = createPreferences(config);
const dotAstroDir = new URL('.astro/', config.root);
const preferences = createPreferences(config, dotAstroDir);
return {
config,
preferences,
Expand Down Expand Up @@ -106,8 +107,9 @@ export function createBaseSettings(config: AstroConfig): AstroSettings {
watchFiles: [],
devToolbarApps: [],
timer: new AstroTimer(),
dotAstroDir: new URL('.astro/', config.root),
dotAstroDir,
latestAstroVersion: undefined, // Will be set later if applicable when the dev server starts
injectedTypes: [],
};
}

Expand Down
11 changes: 6 additions & 5 deletions packages/astro/src/core/dev/restart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ async function createRestartedContainer(
}

const configRE = /.*astro.config.(?:mjs|cjs|js|ts)$/;
const preferencesRE = /.*\.astro\/settings.json$/;

function shouldRestartContainer(
{ settings, inlineConfig, restartInFlight }: Container,
Expand All @@ -39,17 +38,19 @@ function shouldRestartContainer(
if (restartInFlight) return false;

let shouldRestart = false;
const normalizedChangedFile = vite.normalizePath(changedFile);

// If the config file changed, reload the config and restart the server.
if (inlineConfig.configFile) {
shouldRestart = vite.normalizePath(inlineConfig.configFile) === vite.normalizePath(changedFile);
shouldRestart = vite.normalizePath(inlineConfig.configFile) === normalizedChangedFile;
}
// Otherwise, watch for any astro.config.* file changes in project root
else {
const normalizedChangedFile = vite.normalizePath(changedFile);
shouldRestart = configRE.test(normalizedChangedFile);

if (preferencesRE.test(normalizedChangedFile)) {
const settingsPath = vite.normalizePath(
fileURLToPath(new URL('settings.json', settings.dotAstroDir))
);
if (settingsPath.match(normalizedChangedFile)) {
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
shouldRestart = settings.preferences.ignoreNextPreferenceReload ? false : true;

settings.preferences.ignoreNextPreferenceReload = false;
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ export const build = (inlineConfig: AstroInlineConfig) => _build(inlineConfig);
* @experimental The JavaScript API is experimental
*/
// Wrap `_sync` to prevent exposing internal options
export const sync = (inlineConfig: AstroInlineConfig) => _sync({ inlineConfig });
export const sync = (inlineConfig: AstroInlineConfig) => _sync(inlineConfig);
2 changes: 2 additions & 0 deletions packages/astro/src/core/sync/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// TODO: use types.d.ts for backward compatibility. Use astro.d.ts in Astro 5.0
export const REFERENCE_FILE = './types.d.ts';
Loading
Loading