Skip to content

Commit

Permalink
[FIX]:285 - Type proccess.env based off the available secrets in a no… (
Browse files Browse the repository at this point in the history
#333)

* [FIX]:285 - Type proccess.env based off the available secrets in a notebook

* [ADD] - changeset

* [FIX] - linting and formatting

* Style apps page sidebar and header (#340)

* Update sans font (#341)

* File tree functionality and styles (#344)

* Add support for deleting and renaming files (#345)

* Add support for deleting and renaming files

* Fix lint

* Exclude a few directories

* Implement top level create file and folder (#346)

* Homepage UI Rework! (#348)

* inital homepage rework, sections, card style, srcbook to notebook

* fix lil linter error

* move user facing Srcbook (in ref to notebook) to Notebook

* style up to match figma

* some cleanup around purples on create app (#351)

* fix CI bug with pnpm CI mismatch in release (#354)

* Add logic to represent booting state within preview panel and parse stdout from vite to get port (#349)

* feat: add logic to represent booting state within preview panel and parse stdout from vite to get port

* fix: run npm run format

* Add folder delete and rename behavior (#355)

* Add folder delete and rename behavior

* Remove unused files state

* Fix lint warnings

* [FIX] - env type errors

* put the env.d.ts file under root directory instead of src

* remove cell:format

---------

Co-authored-by: Ben Reinhart <[email protected]>
Co-authored-by: versecafe <[email protected]>
Co-authored-by: Ryan Gaus <[email protected]>
  • Loading branch information
4 people authored Oct 14, 2024
1 parent 89e4c7b commit c3e857b
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/five-rats-compare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@srcbook/api': patch
---

Add typing support and errors for environment variables
3 changes: 3 additions & 0 deletions packages/api/server/http.mts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
importSrcbookFromSrcmdFile,
importSrcbookFromSrcmdText,
importSrcbookFromSrcmdUrl,
updateSessionEnvTypeDeclarations,
} from '../srcbook/index.mjs';
import { readdir } from '../fs-utils.mjs';
import { EXAMPLE_SRCBOOKS } from '../srcbook/examples.mjs';
Expand Down Expand Up @@ -276,12 +277,14 @@ router.options('/sessions/:id/secrets/:name', cors());
router.put('/sessions/:id/secrets/:name', cors(), async (req, res) => {
const { id, name } = req.params;
await associateSecretWithSession(name, id);
await updateSessionEnvTypeDeclarations(id);
return res.status(204).end();
});

router.delete('/sessions/:id/secrets/:name', cors(), async (req, res) => {
const { id, name } = req.params;
await disassociateSecretWithSession(name, id);
await updateSessionEnvTypeDeclarations(id);
return res.status(204).end();
});

Expand Down
5 changes: 4 additions & 1 deletion packages/api/srcbook/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,17 @@ export function buildTSPackageJson() {
export function buildTsconfigJson() {
return {
compilerOptions: {
types: [],
strict: true,
module: 'nodenext',
moduleResolution: 'nodenext',
target: 'es2022',
resolveJsonModule: true,
noEmit: true,
allowImportingTsExtensions: true,
noPropertyAccessFromIndexSignature: true,
},
include: ['src/**/*'],
include: ['src/**/*', 'env.d.ts'],
exclude: ['node_modules'],
};
}
43 changes: 42 additions & 1 deletion packages/api/srcbook/index.mts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,16 @@ import { toFormattedJSON } from '../utils.mjs';
import { readdir } from '../fs-utils.mjs';
import { SRCBOOKS_DIR } from '../constants.mjs';
import { EXAMPLE_SRCBOOKS } from '../srcbook/examples.mjs';
import { pathToCodeFile, pathToPackageJson, pathToReadme, pathToTsconfigJson } from './path.mjs';
import {
pathToCodeFile,
pathToPackageJson,
pathToReadme,
pathToSrcbook,
pathToTsconfigJson,
} from './path.mjs';
import { buildJSPackageJson, buildTSPackageJson, buildTsconfigJson } from './config.mjs';
import type { SessionType } from '../types.mjs';
import { getSecretsAssociatedWithSession } from '../config.mjs';

function writeCellOnlyToDisk(srcbookDir: string, cell: PackageJsonCellType | CodeCellType) {
const path =
Expand Down Expand Up @@ -203,6 +210,10 @@ async function createSrcbookDir(basename: string = randomid()) {
const srcPath = Path.join(srcbookDirectoryPath, 'src');
await fs.mkdir(srcPath);

const envTypeDeclarationPath = Path.join(srcbookDirectoryPath, 'env.d.ts');
const envTypeDeclarationFileContent = generateEnvTypesFile({});
await fs.writeFile(envTypeDeclarationPath, envTypeDeclarationFileContent);

return srcbookDirectoryPath;
}

Expand All @@ -217,3 +228,33 @@ export function removeSrcbook(srcbookDir: string) {
export function removeCodeCellFromDisk(srcbookDir: string, filename: string) {
return fs.rm(pathToCodeFile(srcbookDir, filename));
}

export async function updateSessionEnvTypeDeclarations(sessionId: string) {
const sessionSecrets = await getSecretsAssociatedWithSession(sessionId);
if (!Object.entries(sessionSecrets).length) return;
const envTypeDeclarationFileContent = generateEnvTypesFile(sessionSecrets);
const srcbookDir = pathToSrcbook(sessionId);
const envDtsPath = Path.join(srcbookDir, 'env.d.ts');
await fs.writeFile(envDtsPath, envTypeDeclarationFileContent);
}

export function generateEnvTypesFile(secrets: Record<string, string>) {
const envTypes = Object.entries(secrets).length
? Object.keys(secrets)
.map((key) => `readonly ${key}: string;`)
.join('\n')
: '';

return `
declare namespace NodeJS {
interface ProcessEnv {
${envTypes}
}
}
declare var process: {
env: NodeJS.ProcessEnv;
};
`;
}
1 change: 0 additions & 1 deletion packages/web/src/routes/session.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ async function loader({ params }: LoaderFunctionArgs) {
loadSessions(),
loadSession({ id: params.id! }),
]);

return { config, srcbooks, session };
}

Expand Down

0 comments on commit c3e857b

Please sign in to comment.