-
Notifications
You must be signed in to change notification settings - Fork 367
[CRA] Configure create-instant-app for self-hosted backends #2803
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
127 changes: 127 additions & 0 deletions
127
client/packages/create-instant-app/src/backendConfig.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| import fs from 'fs-extra'; | ||
| import os from 'os'; | ||
| import path from 'path'; | ||
| import { fileURLToPath } from 'url'; | ||
| import { afterEach, describe, expect, it } from 'vitest'; | ||
| import { applyBackendConfig, websocketURIFromAPIURI } from './backendConfig.js'; | ||
| import { projectBaseConfig, projectBases } from './projectBase.js'; | ||
|
|
||
| const tempDirs: string[] = []; | ||
| const examplesDir = path.resolve( | ||
| path.dirname(fileURLToPath(import.meta.url)), | ||
| '../../../../examples', | ||
| ); | ||
|
|
||
| const createTempDir = () => { | ||
| const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'backend-config-')); | ||
| tempDirs.push(dir); | ||
| return dir; | ||
| }; | ||
|
|
||
| afterEach(() => { | ||
| for (const dir of tempDirs.splice(0)) { | ||
| fs.removeSync(dir); | ||
| } | ||
| }); | ||
|
|
||
| describe('websocketURIFromAPIURI', () => { | ||
| it.each([ | ||
| ['http://localhost:8888', 'ws://localhost:8888/runtime/session'], | ||
| ['https://instant.example', 'wss://instant.example/runtime/session'], | ||
| [ | ||
| 'https://instant.example/backend/', | ||
| 'wss://instant.example/backend/runtime/session', | ||
| ], | ||
| ])('derives a websocket URI from %s', (apiURI, expected) => { | ||
| expect(websocketURIFromAPIURI(apiURI)).toBe(expected); | ||
| }); | ||
|
|
||
| it('rejects non-HTTP URIs', () => { | ||
| expect(() => websocketURIFromAPIURI('ftp://instant.example')).toThrow( | ||
| 'INSTANT_CLI_API_URI must be a valid HTTP(S) URL', | ||
| ); | ||
| }); | ||
|
|
||
| it('rejects malformed URIs', () => { | ||
| expect(() => websocketURIFromAPIURI('instant.example')).toThrow( | ||
| 'INSTANT_CLI_API_URI must be a valid HTTP(S) URL', | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('applyBackendConfig', () => { | ||
| it('adds API and websocket URIs to a client init', () => { | ||
| const dir = createTempDir(); | ||
| const filePath = path.join(dir, 'src/lib/db.ts'); | ||
| fs.outputFileSync( | ||
| filePath, | ||
| 'export const db = init({\n appId: "app-id",\n});\n', | ||
| ); | ||
|
|
||
| applyBackendConfig('next-js-app-dir', dir, 'http://localhost:8888/'); | ||
|
|
||
| expect(fs.readFileSync(filePath, 'utf8')).toBe( | ||
| 'export const db = init({\n' + | ||
| ' apiURI: "http://localhost:8888",\n' + | ||
| ' websocketURI: "ws://localhost:8888/runtime/session",\n' + | ||
| ' appId: "app-id",\n' + | ||
| '});\n', | ||
| ); | ||
| }); | ||
|
|
||
| it('adds only the API URI to admin init', () => { | ||
| const dir = createTempDir(); | ||
| const clientPath = path.join(dir, 'src/lib/db.ts'); | ||
| const adminPath = path.join(dir, 'src/lib/adminDb.ts'); | ||
| fs.outputFileSync(clientPath, 'export const db = init({\n});\n'); | ||
| fs.outputFileSync(adminPath, 'export const adminDb = init({\n});\n'); | ||
|
|
||
| applyBackendConfig('tanstack-start', dir, 'https://instant.example'); | ||
|
|
||
| expect(fs.readFileSync(adminPath, 'utf8')).toContain( | ||
| 'init({\n apiURI: "https://instant.example",\n', | ||
| ); | ||
| expect(fs.readFileSync(adminPath, 'utf8')).not.toContain('websocketURI'); | ||
| }); | ||
|
|
||
| it('does not update any files if a template cannot be configured', () => { | ||
| const dir = createTempDir(); | ||
| const clientPath = path.join(dir, 'src/lib/db.ts'); | ||
| const adminPath = path.join(dir, 'src/lib/adminDb.ts'); | ||
| const clientContents = 'export const db = init({\n});\n'; | ||
| fs.outputFileSync(clientPath, clientContents); | ||
| fs.outputFileSync(adminPath, 'export const adminDb = unknownInit({});\n'); | ||
|
|
||
| expect(() => | ||
| applyBackendConfig('tanstack-start', dir, 'https://instant.example'), | ||
| ).toThrow('Could not find init({ in scaffolded database file'); | ||
| expect(fs.readFileSync(clientPath, 'utf8')).toBe(clientContents); | ||
| }); | ||
|
|
||
| it('configures the Python client', () => { | ||
| const dir = createTempDir(); | ||
| const filePath = path.join(dir, 'main.py'); | ||
| fs.outputFileSync(filePath, 'db = Instant()\n'); | ||
|
|
||
| applyBackendConfig('python-script', dir, 'https://instant.example/'); | ||
|
|
||
| expect(fs.readFileSync(filePath, 'utf8')).toBe( | ||
| 'db = Instant(api_uri="https://instant.example")\n', | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('project base backend config', () => { | ||
| it.each(projectBases)('%s matches its example template', (base) => { | ||
| for (const file of projectBaseConfig[base].backendConfigFiles) { | ||
| const contents = fs.readFileSync( | ||
| path.join(examplesDir, base, file.path), | ||
| 'utf8', | ||
| ); | ||
| const initializer = | ||
| file.type === 'python' ? 'db = Instant()' : `${file.initializer}({`; | ||
|
|
||
| expect(contents).toContain(initializer); | ||
| } | ||
| }); | ||
| }); |
115 changes: 115 additions & 0 deletions
115
client/packages/create-instant-app/src/backendConfig.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import fs from 'fs-extra'; | ||
| import path from 'path'; | ||
| import { | ||
| projectBaseConfig, | ||
| type BackendConfigFile, | ||
| type ProjectBase, | ||
| } from './projectBase.js'; | ||
|
|
||
| const normalizeAPIURI = (apiURI: string) => apiURI.replace(/\/+$/, ''); | ||
|
|
||
| export const websocketURIFromAPIURI = (apiURI: string) => { | ||
| let websocketURI: URL; | ||
| try { | ||
| websocketURI = new URL(normalizeAPIURI(apiURI)); | ||
| } catch { | ||
| throw new Error('INSTANT_CLI_API_URI must be a valid HTTP(S) URL'); | ||
| } | ||
|
|
||
| if (websocketURI.protocol === 'http:') { | ||
| websocketURI.protocol = 'ws:'; | ||
| } else if (websocketURI.protocol === 'https:') { | ||
| websocketURI.protocol = 'wss:'; | ||
| } else { | ||
| throw new Error('INSTANT_CLI_API_URI must be a valid HTTP(S) URL'); | ||
| } | ||
|
|
||
| websocketURI.pathname = `${websocketURI.pathname.replace(/\/+$/, '')}/runtime/session`; | ||
| websocketURI.search = ''; | ||
| websocketURI.hash = ''; | ||
|
|
||
| return websocketURI.toString(); | ||
| }; | ||
|
|
||
| const injectInitConfig = ({ | ||
| contents, | ||
| initializer, | ||
| apiURI, | ||
| websocketURI, | ||
| }: { | ||
| contents: string; | ||
| initializer: string; | ||
| apiURI: string; | ||
| websocketURI?: string; | ||
| }) => { | ||
| const initStart = `${initializer}({`; | ||
| if (!contents.includes(initStart)) { | ||
| throw new Error(`Could not find ${initStart} in scaffolded database file`); | ||
| } | ||
|
|
||
| const config = [ | ||
| ` apiURI: ${JSON.stringify(apiURI)},`, | ||
| websocketURI ? ` websocketURI: ${JSON.stringify(websocketURI)},` : null, | ||
| ] | ||
| .filter(Boolean) | ||
| .join('\n'); | ||
|
|
||
| return contents.replace(initStart, `${initStart}\n${config}`); | ||
| }; | ||
|
|
||
| const injectPythonConfig = (contents: string, apiURI: string) => { | ||
| const initStart = 'db = Instant()'; | ||
| if (!contents.includes(initStart)) { | ||
| throw new Error(`Could not find ${initStart} in scaffolded database file`); | ||
| } | ||
|
|
||
| return contents.replace( | ||
| initStart, | ||
| `db = Instant(api_uri=${JSON.stringify(apiURI)})`, | ||
| ); | ||
| }; | ||
|
|
||
| const injectBackendConfig = ( | ||
| file: BackendConfigFile, | ||
| contents: string, | ||
| apiURI: string, | ||
| websocketURI: string, | ||
| ) => { | ||
| if (file.type === 'python') { | ||
| return injectPythonConfig(contents, apiURI); | ||
| } | ||
|
|
||
| return injectInitConfig({ | ||
| contents, | ||
| initializer: file.initializer, | ||
| apiURI, | ||
| websocketURI: file.websocket ? websocketURI : undefined, | ||
| }); | ||
| }; | ||
|
|
||
| export const applyBackendConfig = ( | ||
| base: ProjectBase, | ||
| projectDir: string, | ||
| apiURI: string, | ||
| ) => { | ||
| const normalizedAPIURI = normalizeAPIURI(apiURI); | ||
| const websocketURI = websocketURIFromAPIURI(normalizedAPIURI); | ||
|
|
||
| const updates = projectBaseConfig[base].backendConfigFiles.map((file) => { | ||
| const filePath = path.join(projectDir, file.path); | ||
| const contents = fs.readFileSync(filePath, 'utf8'); | ||
| return { | ||
| filePath, | ||
| contents: injectBackendConfig( | ||
| file, | ||
| contents, | ||
| normalizedAPIURI, | ||
| websocketURI, | ||
| ), | ||
| }; | ||
| }); | ||
|
|
||
| for (const update of updates) { | ||
| fs.writeFileSync(update.filePath, update.contents); | ||
| } | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Uncaught
applyBackendConfigfailure crashes mid-scaffold, leaving a broken half-set-up project.This call isn't wrapped in error handling. If
INSTANT_CLI_API_URIis malformed, or a scaffolded file's expected initializer text (init({/db = Instant()) doesn't match (e.g. future template drift),applyBackendConfigthrows and the whole process dies with a raw stack trace — afterprojectDiralready exists on disk but before rule files, env file, dependency install, package renaming, or git init have run.🔧 Proposed fix: surface a clear, non-crashing error
if (process.env.INSTANT_CLI_API_URI) { - applyBackendConfig( - project.base, - projectDir, - process.env.INSTANT_CLI_API_URI, - ); + try { + applyBackendConfig( + project.base, + projectDir, + process.env.INSTANT_CLI_API_URI, + ); + } catch (err) { + console.error( + `Warning: could not apply self-hosted backend config: ${ + err instanceof Error ? err.message : err + }`, + ); + console.error( + 'You may need to manually set apiURI/websocketURI in your backend init.', + ); + } }📝 Committable suggestion
🤖 Prompt for AI Agents