diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4abe954c..0c4ac783 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -162,7 +162,7 @@ jobs: - name: Test JavaScript wrappers and example runners if: steps.select.outputs.typescript == 'true' run: | - node --test scripts/materialize-sqlite-sources.test.mjs + node --test scripts/materialize-sqlite-sources.test.mjs scripts/companion-materialize.test.mjs node --test scripts/mikro-orm-metro.test.mjs bun --cwd packages/react-native-nitro-sqlite build bun --cwd packages/integrations/react-native/typeorm build diff --git a/bun.lock b/bun.lock index dd6d3e4b..35853ce3 100644 --- a/bun.lock +++ b/bun.lock @@ -185,6 +185,85 @@ "babel-plugin-inline-import": "3.0.0", }, }, + "packages/integrations/nitro-ui/drizzle": { + "name": "nitro-sqlite-drizzle", + "version": "11.0.0", + "devDependencies": { + "drizzle-orm": "0.45.4", + "typescript": "^5.8.3", + }, + "peerDependencies": { + "drizzle-orm": ">=0.45.4 <1.0.0", + "nitro-sqlite": ">=11.0.0-0", + "react": ">=17.0.0", + }, + }, + "packages/integrations/nitro-ui/kysely": { + "name": "nitro-sqlite-kysely", + "version": "11.0.0", + "dependencies": { + "kysely-generic-sqlite": "^2.0.1", + }, + "devDependencies": { + "@types/node": "^25.0.0", + "better-sqlite3": "^12.11.1", + "kysely": "0.29.9", + "nitro-sqlite": "11.0.0", + "typescript": "^6.0.3", + }, + "peerDependencies": { + "kysely": "^0.29.9", + "nitro-sqlite": ">=11.0.0-0", + }, + }, + "packages/integrations/nitro-ui/mikro-orm": { + "name": "nitro-sqlite-mikro-orm", + "version": "11.0.0", + "dependencies": { + "kysely-generic-sqlite": "^2.0.1", + "nitro-sqlite-kysely": "11.0.0", + }, + "devDependencies": { + "@mikro-orm/sql": "7.2.13", + "@types/node": "^25.0.0", + "better-sqlite3": "^12.11.1", + "kysely": "0.29.9", + "nitro-sqlite": "11.0.0", + "typescript": "^6.0.3", + }, + "peerDependencies": { + "@mikro-orm/sql": "~7.2.13", + "kysely": "^0.29.9", + "nitro-sqlite": ">=11.0.0-0", + }, + }, + "packages/integrations/nitro-ui/typeorm": { + "name": "nitro-sqlite-typeorm", + "version": "11.0.0", + "devDependencies": { + "nitro-sqlite": "11.0.0", + "typeorm": "1.1.2", + "typescript": "^6.0.3", + }, + "peerDependencies": { + "nitro-sqlite": ">=11.0.0-0", + "typeorm": "^1.1.2", + }, + }, + "packages/integrations/nitro-ui/vec": { + "name": "nitro-sqlite-vec", + "version": "11.0.0", + "dependencies": { + "nitro-core": "1.0.0-alpha.nightly.137.gd4793c40b8b8", + }, + "devDependencies": { + "nitrogen": "1.0.0-alpha.nightly.137.gd4793c40b8b8", + "typescript": "^6.0.3", + }, + "peerDependencies": { + "nitro-sqlite": ">=11.0.0-0", + }, + }, "packages/integrations/react-native/drizzle": { "name": "react-native-nitro-sqlite-drizzle", "version": "10.5.0", @@ -1597,7 +1676,7 @@ "before-after-hook": ["before-after-hook@2.2.3", "", {}, "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ=="], - "better-sqlite3": ["better-sqlite3@13.2.0", "", { "dependencies": { "node-addon-api": "^8.0.0" } }, "sha512-Z8Q/9x/uNyKxA1v4FNodyItRVRw1TeKBrmj32JhxhR0ceNcBY+wMobt/Bv7M7TzwPAXjnZRtNaEsATnUZSKWZQ=="], + "better-sqlite3": ["better-sqlite3@12.11.1", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA=="], "big-integer": ["big-integer@1.6.52", "", {}, "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg=="], @@ -2711,8 +2790,18 @@ "nitro-sqlite-core": ["nitro-sqlite-core@workspace:packages/nitro-sqlite-core"], + "nitro-sqlite-drizzle": ["nitro-sqlite-drizzle@workspace:packages/integrations/nitro-ui/drizzle"], + "nitro-sqlite-drizzle-core": ["nitro-sqlite-drizzle-core@workspace:packages/nitro-sqlite-drizzle-core"], + "nitro-sqlite-kysely": ["nitro-sqlite-kysely@workspace:packages/integrations/nitro-ui/kysely"], + + "nitro-sqlite-mikro-orm": ["nitro-sqlite-mikro-orm@workspace:packages/integrations/nitro-ui/mikro-orm"], + + "nitro-sqlite-typeorm": ["nitro-sqlite-typeorm@workspace:packages/integrations/nitro-ui/typeorm"], + + "nitro-sqlite-vec": ["nitro-sqlite-vec@workspace:packages/integrations/nitro-ui/vec"], + "nitrogen": ["nitrogen@1.0.0-alpha.nightly.138.g43e09c161101", "", { "dependencies": { "chalk": "^5.3.0", "nitro-core": "1.0.0-alpha.nightly.138.g43e09c161101", "ts-morph": "^28.0.0", "yargs": "^18.1.0", "zod": "^4.4.3" }, "bin": { "nitrogen": "bin/nitrogen.js" } }, "sha512-cFf+u0MQqy7e1uipRBoipkYVHMxN8KaB2LUs/9G0BHQPMZJu7KjVt7t1moPicBtrMPfZPDW/aClpUylYfNDpkA=="], "nocache": ["nocache@3.0.4", "", {}, "sha512-WDD0bdg9mbq6F4mRxEYcPWwfA1vxd0mrvKOyxI7Xj/atfRHVeutzuWByG//jfm4uPzp0y4Kj051EORCBSQMycw=="], @@ -4317,6 +4406,10 @@ "nitro-sqlite-core/nitro-core": ["nitro-core@1.0.0-alpha.nightly.86.g15e19db42041", "", {}, "sha512-ClH75zDyCx2frd5CL8yhz35m5aIPveWPDdnOX86OWADGU2tq06vkc5rkVbuaNTnCH6FJLutTXPg7HxEFVZfrJQ=="], + "nitro-sqlite-drizzle/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "nitro-sqlite-vec/nitrogen": ["nitrogen@1.0.0-alpha.nightly.137.gd4793c40b8b8", "", { "dependencies": { "chalk": "^5.3.0", "nitro-core": "1.0.0-alpha.nightly.137.gd4793c40b8b8", "ts-morph": "^28.0.0", "yargs": "^18.1.0", "zod": "^4.4.3" }, "bin": { "nitrogen": "bin/nitrogen.js" } }, "sha512-U+/MugSAIfM55gzXCFyND9vb2c4FCOWROr/TlYEHE3Bt+55lXmxEFsmK/ohdGL3n7jiDrrWcR2gf7uf55C9eHw=="], + "nitrogen/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], "nitrogen/nitro-core": ["nitro-core@1.0.0-alpha.nightly.138.g43e09c161101", "", {}, "sha512-PTOpc4jUIzfsyWUWJgXT+3of9xqbOBCenS6dkhrEmYPvHsZ+VKMK61RO+ph38UKVZLAd/zLij3uh2ZU0g1AtYQ=="], @@ -4407,6 +4500,8 @@ "react-native-nitro-modules/nitro-core": ["nitro-core@1.0.0-alpha.nightly.138.g43e09c161101", "", {}, "sha512-PTOpc4jUIzfsyWUWJgXT+3of9xqbOBCenS6dkhrEmYPvHsZ+VKMK61RO+ph38UKVZLAd/zLij3uh2ZU0g1AtYQ=="], + "react-native-nitro-sqlite/better-sqlite3": ["better-sqlite3@13.2.0", "", { "dependencies": { "node-addon-api": "^8.0.0" } }, "sha512-Z8Q/9x/uNyKxA1v4FNodyItRVRw1TeKBrmj32JhxhR0ceNcBY+wMobt/Bv7M7TzwPAXjnZRtNaEsATnUZSKWZQ=="], + "react-native-nitro-sqlite-drizzle/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], "react-native-nitro-sqlite-example/@babel/core": ["@babel/core@7.29.13", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.13", "@babel/helper-compilation-targets": "^7.29.13", "@babel/helper-module-transforms": "^7.29.13", "@babel/helpers": "^7.29.13", "@babel/parser": "^7.29.13", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.13", "@babel/types": "^7.29.11", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw=="], @@ -4415,8 +4510,6 @@ "react-native-nitro-sqlite-example/@types/node": ["@types/node@22.19.0", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-xpr/lmLPQEj+TUnHmR+Ab91/glhJvsqcjB+yY0Ix9GO70H6Lb4FHH5GeqdOE5btAx7eIMwuHkp4H2MSkLcqWbA=="], - "react-native-nitro-sqlite-kysely/better-sqlite3": ["better-sqlite3@12.11.1", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA=="], - "react-native-nitro-sqlite-macos-example/@react-native-community/cli": ["@react-native-community/cli@19.1.2", "", { "dependencies": { "@react-native-community/cli-clean": "19.1.2", "@react-native-community/cli-config": "19.1.2", "@react-native-community/cli-doctor": "19.1.2", "@react-native-community/cli-server-api": "19.1.2", "@react-native-community/cli-tools": "19.1.2", "@react-native-community/cli-types": "19.1.2", "chalk": "^4.1.2", "commander": "^9.4.1", "deepmerge": "^4.3.0", "execa": "^5.0.0", "find-up": "^5.0.0", "fs-extra": "^8.1.0", "graceful-fs": "^4.1.3", "prompts": "^2.4.2", "semver": "^7.5.2" }, "bin": { "rnc-cli": "build/bin.js" } }, "sha512-b28TLqODMgQRx6f4gbHoHYpnKyFbWzJkIk3+Ggpad/at493KfGQ+WvKg1sts/st8mxzmbk0T6lCc/9A3QoFKkQ=="], "react-native-nitro-sqlite-macos-example/@react-native-community/cli-platform-android": ["@react-native-community/cli-platform-android@19.1.2", "", { "dependencies": { "@react-native-community/cli-config-android": "19.1.2", "@react-native-community/cli-tools": "19.1.2", "chalk": "^4.1.2", "execa": "^5.0.0", "logkitty": "^0.7.1" } }, "sha512-eMryTlSSTl3JK/tZTaMaMgHec9qu+eQj+3A15qmBdj2ac3p/hiauwAe4q35rz5XABw1cJCuyn+s469YsdTllaw=="], @@ -4437,8 +4530,6 @@ "react-native-nitro-sqlite-macos-example/react-native-nitro-modules": ["react-native-nitro-modules@0.37.2", "", { "dependencies": { "nitro-core": "0.37.2" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-Odnrq/p6/q0R01qZlkqeXu9VHHMuGEnZZmyxMvehEu6QiACNHhBCmAHgyBDqOSo9Lb3G0TscFAT+HG0uxsR/GA=="], - "react-native-nitro-sqlite-mikro-orm/better-sqlite3": ["better-sqlite3@12.11.1", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA=="], - "react-native-nitro-sqlite-vec/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], "read-pkg/normalize-package-data": ["normalize-package-data@2.5.0", "", { "dependencies": { "hosted-git-info": "^2.1.4", "resolve": "^1.10.0", "semver": "2 || 3 || 4 || 5", "validate-npm-package-license": "^3.0.1" } }, "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA=="], @@ -4513,8 +4604,6 @@ "typedoc/minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="], - "typeorm/better-sqlite3": ["better-sqlite3@12.11.1", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA=="], - "typescript-eslint/@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.46.3", "", { "dependencies": { "@eslint-community/regexpp": "^4.10.0", "@typescript-eslint/scope-manager": "8.46.3", "@typescript-eslint/type-utils": "8.46.3", "@typescript-eslint/utils": "8.46.3", "@typescript-eslint/visitor-keys": "8.46.3", "graphemer": "^1.4.0", "ignore": "^7.0.0", "natural-compare": "^1.4.0", "ts-api-utils": "^2.1.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.46.3", "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-sbaQ27XBUopBkRiuY/P9sWGOWUW4rl8fDoHIUmLpZd8uldsTyB4/Zg6bWTegPoTLnKj9Hqgn3QD6cjPNB32Odw=="], "typescript-eslint/@typescript-eslint/parser": ["@typescript-eslint/parser@8.46.3", "", { "dependencies": { "@typescript-eslint/scope-manager": "8.46.3", "@typescript-eslint/types": "8.46.3", "@typescript-eslint/typescript-estree": "8.46.3", "@typescript-eslint/visitor-keys": "8.46.3", "debug": "^4.3.4" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-6m1I5RmHBGTnUGS113G04DMu3CpSdxCAU/UvtjNWL4Nuf3MW9tQhiJqRlHzChIkhy6kZSAQmc+I1bcGjE3yNKg=="], @@ -5533,6 +5622,8 @@ "mocha/minimatch/brace-expansion": ["brace-expansion@5.0.12", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="], + "nitro-sqlite-vec/nitrogen/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], + "nitro-sqlite/nitrogen/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], "normalize-package-data/hosted-git-info/lru-cache": ["lru-cache@6.0.0", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA=="], diff --git a/package.json b/package.json index a5022818..8597a30c 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "workspaces": [ "packages/*", "packages/integrations/react-native/*", + "packages/integrations/nitro-ui/*", "examples/react-native", "examples/react-native/macos", "examples/react-native/expo", diff --git a/packages/integrations/nitro-ui/drizzle/.gitignore b/packages/integrations/nitro-ui/drizzle/.gitignore new file mode 100644 index 00000000..7dc101c5 --- /dev/null +++ b/packages/integrations/nitro-ui/drizzle/.gitignore @@ -0,0 +1 @@ +/src/*.ts diff --git a/packages/integrations/nitro-ui/drizzle/.npmignore b/packages/integrations/nitro-ui/drizzle/.npmignore new file mode 100644 index 00000000..f22a0fd0 --- /dev/null +++ b/packages/integrations/nitro-ui/drizzle/.npmignore @@ -0,0 +1,3 @@ +src/__tests__/ +.tsbuild/ +tsconfig.tsbuildinfo diff --git a/packages/integrations/nitro-ui/drizzle/LICENSE b/packages/integrations/nitro-ui/drizzle/LICENSE new file mode 100644 index 00000000..01aa59f2 --- /dev/null +++ b/packages/integrations/nitro-ui/drizzle/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2024 Marc Rousavy & Christoph Pader +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/integrations/nitro-ui/drizzle/README.md b/packages/integrations/nitro-ui/drizzle/README.md new file mode 100644 index 00000000..b6df011d --- /dev/null +++ b/packages/integrations/nitro-ui/drizzle/README.md @@ -0,0 +1,87 @@ +# nitro-sqlite-drizzle + +[Drizzle ORM](https://orm.drizzle.team) driver for `nitro-sqlite`. + +## Installation + +This 11.0.0 pre-release package is not published to npm. Build and install the matching +SQLite and Drizzle archives using the [companion installation guide](../../../../docs/content/docs/integrations/orms/index.mdx). +Install `drizzle-orm@0.45.4` and the app's React version alongside them. Each archive +includes the driver source. Use `nitro-sqlite` with `nitro-sqlite-drizzle` in NitroUI apps. + + +## Usage + +```ts +import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core' +import { open } from 'nitro-sqlite' +import { drizzle } from 'nitro-sqlite-drizzle' + +const users = sqliteTable('users', { + id: integer('id').primaryKey(), + name: text('name').notNull(), +}) + +const db = drizzle(open({ name: 'app.sqlite' })) + +await db.insert(users).values({ id: 1, name: 'Ada' }) +const rows = await db.select().from(users) +``` + +Every query is asynchronous. Inside `db.transaction()`, run queries through `tx`: a query awaited through `db` waits for the transaction and never completes. + +See the [Drizzle ORM integration guide](../../../../docs/content/docs/integrations/orms/drizzle.mdx) for migrations, `useMigrations`, and transactions. + + +## Migrations + +SQLite schema changes are SQL statements. Drizzle Kit bundles them with an ordered +journal, and the driver records each completed migration in `__drizzle_migrations`. +Pending migrations run in one transaction. A failure rolls them back together. + +Generate a bundled `migrations.js` module with Drizzle Kit, then pass that module +to the driver. Configure your app's bundler to import its `.sql` files as strings. + +```ts +import { migrate } from 'nitro-sqlite-drizzle' +import migrations from './drizzle/migrations' + +await migrate(db, migrations) +``` + +In a React component, `useMigrations(db, migrations)` returns `{ success, error }`. +Wait for `success` before rendering components that query the migrated schema. +Changing the database or migration bundle resets the hook's state. Migrations +already queued still finish after a component unmounts. + +```tsx +import { useMigrations } from 'nitro-sqlite-drizzle' + +function DatabaseGate() { + const { success, error } = useMigrations(db, migrations) + if (error) throw error + if (!success) return null + return +} +``` + +Calls to `migrate` and `useMigrations` sharing a connection run in sequence. +Closing the connection remains the caller's responsibility. Close it only after +all queries, transactions, and migrations finish. + +## Transactions and results + +Use the callback's `tx` handle for every query inside a transaction, and await +nested transactions before using their parent again. Nested transactions use +SQLite savepoints. An escaped callback error rolls back its changes. Transaction +handles and their prepared queries reject after their callback ends. + +Drizzle selected fields decode positional SQLite rows, so joins preserve columns +with repeated names. Queries without selected fields return objects keyed by +column name. `run()` returns the native raw result with `rowsAffected`, optional +`insertId`, `columnNames`, and positional `rows`. Binary views used as parameters +bind only their own bytes, rather than the entire backing buffer. + +This driver supports Drizzle ORM 0.45.x. It uses asynchronous queries and does not +own or close the supplied SQLite connection. Its prepared-query wrappers do not +retain native statements and need no disposal. diff --git a/packages/integrations/nitro-ui/drizzle/package.json b/packages/integrations/nitro-ui/drizzle/package.json new file mode 100644 index 00000000..76495340 --- /dev/null +++ b/packages/integrations/nitro-ui/drizzle/package.json @@ -0,0 +1,64 @@ +{ + "name": "nitro-sqlite-drizzle", + "version": "11.0.0", + "description": "Drizzle ORM driver for nitro-sqlite.", + "source": "./src/index.ts", + "main": "./src/index.ts", + "types": "./src/index.ts", + "files": [ + "src", + "!**/__tests__", + "README.md", + "scripts", + "LICENSE" + ], + "scripts": { + "typecheck": "node scripts/materialize.mjs && tsc --noEmit", + "prepublishOnly": "node scripts/materialize.mjs && tsc --noEmit", + "materialize": "node scripts/materialize.mjs", + "prepack": "node scripts/materialize.mjs && tsc --noEmit", + "pack": "bun pm pack" + }, + "keywords": [ + "sqlite", + "drizzle", + "drizzle-orm", + "orm", + "ios", + "android", + "nitro-ui" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/margelo/nitro-sqlite.git" + }, + "author": "Christoph Pader", + "license": "MIT", + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "access": "public" + }, + "peerDependencies": { + "drizzle-orm": ">=0.45.4 <1.0.0", + "react": ">=17.0.0", + "nitro-sqlite": ">=11.0.0-0" + }, + "devDependencies": { + "drizzle-orm": "0.45.4", + "typescript": "^5.8.3" + }, + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./driver": "./src/driver.ts", + "./session": "./src/session.ts", + "./migrator": "./src/migrator.ts", + "./package.json": "./package.json", + "./src/*.ts": "./src/*.ts", + "./src/*": "./src/*.ts" + }, + "type": "module", + "module": "./src/index.ts" +} diff --git a/packages/integrations/nitro-ui/drizzle/scripts/materialize.mjs b/packages/integrations/nitro-ui/drizzle/scripts/materialize.mjs new file mode 100644 index 00000000..6b4c0259 --- /dev/null +++ b/packages/integrations/nitro-ui/drizzle/scripts/materialize.mjs @@ -0,0 +1,35 @@ +import { existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const packageDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const sharedDirectory = resolve( + packageDirectory, + '../../../nitro-sqlite-drizzle-core/src', +) +const sourceDirectory = join(packageDirectory, 'src') +const packageName = JSON.parse( + readFileSync(join(packageDirectory, 'package.json'), 'utf8'), +).name +const sqlitePackage = packageName.replace(/-drizzle$/, '') + +// Packed packages retain their materialized source and do not need the workspace. +if (existsSync(sharedDirectory)) { + const { writeGeneratedFile } = await import( + '../../../../nitro-sqlite-core/scripts/materialize-sources.mjs' + ) + mkdirSync(sourceDirectory, { recursive: true }) + for (const file of readdirSync(sharedDirectory)) { + if (!file.endsWith('.ts')) continue + const content = readFileSync( + join(sharedDirectory, file), + 'utf8', + ).replaceAll('react-native-nitro-sqlite', sqlitePackage) + const destination = join(sourceDirectory, file) + writeGeneratedFile(destination, Buffer.from(content)) + } +} else if (!existsSync(join(sourceDirectory, 'index.ts'))) { + throw new Error( + 'Drizzle source is missing. Build the package from the workspace before packing it.', + ) +} diff --git a/packages/integrations/nitro-ui/drizzle/tsconfig.json b/packages/integrations/nitro-ui/drizzle/tsconfig.json new file mode 100644 index 00000000..8a325fa9 --- /dev/null +++ b/packages/integrations/nitro-ui/drizzle/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "target": "ESNext", + "lib": ["ESNext"], + "noUncheckedIndexedAccess": true, + "noImplicitReturns": true, + "types": [] + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/integrations/nitro-ui/kysely/.gitignore b/packages/integrations/nitro-ui/kysely/.gitignore new file mode 100644 index 00000000..d74f5eb4 --- /dev/null +++ b/packages/integrations/nitro-ui/kysely/.gitignore @@ -0,0 +1,2 @@ +# Direct TypeScript sources are generated; authored tests live in tests/. +/src/*.ts diff --git a/packages/integrations/nitro-ui/kysely/LICENSE b/packages/integrations/nitro-ui/kysely/LICENSE new file mode 100644 index 00000000..01aa59f2 --- /dev/null +++ b/packages/integrations/nitro-ui/kysely/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2024 Marc Rousavy & Christoph Pader +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/integrations/nitro-ui/kysely/README.md b/packages/integrations/nitro-ui/kysely/README.md new file mode 100644 index 00000000..1f208900 --- /dev/null +++ b/packages/integrations/nitro-ui/kysely/README.md @@ -0,0 +1,20 @@ +# Nitro SQLite for Kysely + +Use Kysely's typed SQL builder with a local Nitro SQLite database on NitroUI. Install `nitro-sqlite-kysely`, `kysely@^0.29.9`, and the [Nitro SQLite native dependencies](https://sqlite.margelo.com/docs). + +For this unpublished 11.0.0 pre-release, build and install local archives for the adapter and companion. See the [companion installation guide](../../../../docs/content/docs/integrations/orms/index.mdx) for packing steps and peer dependencies. + +```ts +import { Kysely } from 'kysely' +import { createNitroSQLiteDialect } from 'nitro-sqlite-kysely' + +interface Database { + notes: { id: number; title: string } +} + +const db = new Kysely({ + dialect: createNitroSQLiteDialect({ name: 'notes.sqlite' }), +}) +``` + +The first query opens an independent native handle. Await your queries and transactions before closing it with `await db.destroy()`. See the [Kysely quick start](https://sqlite.margelo.com/docs/integrations/orms#kysely) for table creation and queries, and the [Kysely guide](https://sqlite.margelo.com/docs/integrations/orms/kysely) for transactions and migrations. diff --git a/packages/integrations/nitro-ui/kysely/package.json b/packages/integrations/nitro-ui/kysely/package.json new file mode 100644 index 00000000..ae56eda3 --- /dev/null +++ b/packages/integrations/nitro-ui/kysely/package.json @@ -0,0 +1,54 @@ +{ + "name": "nitro-sqlite-kysely", + "version": "11.0.0", + "description": "Kysely SQLite dialect for NitroUI using Nitro SQLite.", + "source": "./src/index.ts", + "main": "./src/index.ts", + "types": "./src/index.ts", + "files": [ + "src", + "scripts", + "README.md", + "LICENSE", + "tsconfig.json" + ], + "scripts": { + "materialize": "node scripts/materialize.mjs", + "typecheck": "node scripts/materialize.mjs && tsc --noEmit", + "prepack": "node scripts/materialize.mjs && tsc --noEmit", + "prepublishOnly": "node scripts/materialize.mjs && tsc --noEmit", + "test": "node scripts/materialize.mjs && node --experimental-strip-types --test tests/*.test.ts", + "pack": "bun pm pack" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/margelo/nitro-sqlite.git" + }, + "author": "Christoph Pader", + "license": "MIT", + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "access": "public" + }, + "dependencies": { + "kysely-generic-sqlite": "^2.0.1" + }, + "peerDependencies": { + "kysely": "^0.29.9", + "nitro-sqlite": ">=11.0.0-0" + }, + "devDependencies": { + "kysely": "0.29.9", + "nitro-sqlite": "11.0.0", + "better-sqlite3": "^12.11.1", + "@types/node": "^25.0.0", + "typescript": "^6.0.3" + }, + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./package.json": "./package.json" + } +} diff --git a/packages/integrations/nitro-ui/kysely/scripts/materialize.mjs b/packages/integrations/nitro-ui/kysely/scripts/materialize.mjs new file mode 100644 index 00000000..c81853d2 --- /dev/null +++ b/packages/integrations/nitro-ui/kysely/scripts/materialize.mjs @@ -0,0 +1,19 @@ +import { existsSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const packageDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const sharedHelper = resolve( + packageDirectory, + '../../../../shared/orm/materialize-sources.mjs', +) +if (existsSync(sharedHelper)) { + const { materializeOrmSources } = await import( + pathToFileURL(sharedHelper).href + ) + materializeOrmSources(packageDirectory) +} else if (!existsSync(join(packageDirectory, 'src/index.ts'))) { + throw new Error( + 'ORM source is missing. Prepare the package from the workspace before packing it.', + ) +} diff --git a/packages/integrations/nitro-ui/kysely/tests/dialect.test.ts b/packages/integrations/nitro-ui/kysely/tests/dialect.test.ts new file mode 100644 index 00000000..9353c76f --- /dev/null +++ b/packages/integrations/nitro-ui/kysely/tests/dialect.test.ts @@ -0,0 +1,16 @@ +import * as nodeModule from 'node:module' +import { registerBehaviorTests } from '../../../../../shared/orm/kysely/tests/behavior.ts' +import { resolve } from './resolve.mjs' + +if (nodeModule.registerHooks) { + nodeModule.registerHooks({ resolve }) +} else { + nodeModule.register('./resolve.mjs', import.meta.url) +} + +const { open, resetAllDatabases } = await import( + '../../../../nitro-sqlite/src/mock.ts' +) +const { createNitroSQLiteDialect } = await import('../src/index.ts') + +registerBehaviorTests({ open, resetAllDatabases, createNitroSQLiteDialect }) diff --git a/packages/integrations/nitro-ui/kysely/tests/nativeMock.ts b/packages/integrations/nitro-ui/kysely/tests/nativeMock.ts new file mode 100644 index 00000000..1d28b725 --- /dev/null +++ b/packages/integrations/nitro-ui/kysely/tests/nativeMock.ts @@ -0,0 +1,25 @@ +import { open as openMock } from '../../../../nitro-sqlite/src/mock.ts' + +export const nativeHooks: { + beforeExecute?: ( + sql: string, + database: ReturnType, + ) => Promise | undefined + beforeClose?: () => void +} = {} + +export function open(options: Parameters[0]) { + const database = openMock(options) + const executeAsync: typeof database.executeAsync = async (sql, params) => { + await nativeHooks.beforeExecute?.(sql, database) + return database.executeAsync(sql, params) + } + return { + ...database, + executeAsync, + close: () => { + nativeHooks.beforeClose?.() + database.close() + }, + } +} diff --git a/packages/integrations/nitro-ui/kysely/tests/resolve.mjs b/packages/integrations/nitro-ui/kysely/tests/resolve.mjs new file mode 100644 index 00000000..c10b79f7 --- /dev/null +++ b/packages/integrations/nitro-ui/kysely/tests/resolve.mjs @@ -0,0 +1,22 @@ +import { extname } from 'node:path' + +const packagesUrl = new URL('../../../../', import.meta.url).href + +// Resolve Metro-style imports to the workspace sources and replace the native entry point. +export function resolve(specifier, context, nextResolve) { + if (specifier === 'nitro-sqlite') { + return nextResolve( + new URL('./nativeMock.ts', import.meta.url).href, + context, + ) + } + if ( + context.parentURL?.startsWith(packagesUrl) && + !context.parentURL.includes('/node_modules/') && + (specifier.startsWith('./') || specifier.startsWith('../')) && + extname(specifier) === '' + ) { + return nextResolve(`${specifier}.ts`, context) + } + return nextResolve(specifier, context) +} diff --git a/packages/integrations/nitro-ui/kysely/tsconfig.json b/packages/integrations/nitro-ui/kysely/tsconfig.json new file mode 100644 index 00000000..eef31c93 --- /dev/null +++ b/packages/integrations/nitro-ui/kysely/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "target": "ESNext", + "lib": ["ESNext"], + "noUncheckedIndexedAccess": true, + "noImplicitReturns": true, + "types": [], + "paths": { + "nitro-sqlite": ["../../../nitro-sqlite/src/index.ts"], + "nitro-sqlite-kysely": ["./src/index.ts"] + } + }, + "include": ["src"] +} diff --git a/packages/integrations/nitro-ui/mikro-orm/.gitignore b/packages/integrations/nitro-ui/mikro-orm/.gitignore new file mode 100644 index 00000000..d74f5eb4 --- /dev/null +++ b/packages/integrations/nitro-ui/mikro-orm/.gitignore @@ -0,0 +1,2 @@ +# Direct TypeScript sources are generated; authored tests live in tests/. +/src/*.ts diff --git a/packages/integrations/nitro-ui/mikro-orm/LICENSE b/packages/integrations/nitro-ui/mikro-orm/LICENSE new file mode 100644 index 00000000..01aa59f2 --- /dev/null +++ b/packages/integrations/nitro-ui/mikro-orm/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2024 Marc Rousavy & Christoph Pader +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/integrations/nitro-ui/mikro-orm/README.md b/packages/integrations/nitro-ui/mikro-orm/README.md new file mode 100644 index 00000000..9314847a --- /dev/null +++ b/packages/integrations/nitro-ui/mikro-orm/README.md @@ -0,0 +1,21 @@ +# Nitro SQLite for MikroORM + +`NitroSQLiteDriver` runs MikroORM 7.2 queries against a local Nitro SQLite database in NitroUI. + +For this unpublished 11.0.0 pre-release, build and install local archives for the adapter and companion. See the [companion installation guide](../../../../docs/content/docs/integrations/orms/index.mdx) for packing steps and peer dependencies. + +Prepare MikroORM and the driver in one browser bundle, then import both from that bundle. Follow the [MikroORM guide](../../../../docs/content/docs/integrations/orms/mikro-orm.mdx#configure-nitroui) for the preparation script, environment shim, and import paths. Use explicit entities and a `dbName`. Filesystem entity discovery is unsupported on a device. + +Initialize a `Buffer` implementation with `base64url` support before importing ORM code. Entity discovery must use explicit entity classes or schemas. Keep the ORM's entity metadata and database initialization outside render functions. + +Use MikroORM's `onCreateConnection` to configure each SQLite handle before its first query. Set `PRAGMA busy_timeout` in the hook to configure how long SQLite waits for locks, in milliseconds. The hook runs again after reconnecting. A replica keeps its explicit `dbName`, `driverOptions`, and hook across reconnects. A replica uses the current ORM default for each omitted setting. + +SQL dumps are trusted executable SQL, including their PRAGMA and transaction commands. Pass SQL dumps to `orm.em.getConnection().executeDump(sql)`. Run the import outside `em.transactional()` callbacks. The callback holds the connection that the dump waits for, so awaiting a dump inside the callback deadlocks. + +SQLite runs the dump's statements and transaction commands in order on one connection. The driver rejects a dump containing NUL before running any SQL. If a statement fails or the dump leaves its own transaction or outermost savepoint open, the driver rejects the import and rolls back that scope before queued work can run. Earlier commits stay committed. If you issued `BEGIN` yourself, finish that transaction and keep other work off the connection until it ends. If dump rollback fails, reconnect before using the connection again. + +A rejected dump restores the previous `foreign_keys` and `defer_foreign_keys` settings before queued work runs. A successful dump keeps its settings. Cleanup does not restore unrelated PRAGMAs. Before restoring deferral, the driver checks for foreign-key violations in every attached schema, including `temp`. If violations remain, it leaves deferral unchanged and blocks further queries on the handle. Cleanup never disables deferral while violations remain, and cannot recover violation tracking already cleared by the dump's own SQL. Reconnect if rollback or setting restoration fails. Reconnecting closes the old handle and rolls back any remaining caller-owned transaction. + +The driver does not support MikroORM or Kysely query streaming. Use bounded queries with `limit` to read large result sets in pages. For raw Kysely binds, convert `Date` values to the format used by the target column. Pass a decimal string when you need to preserve a `bigint` exactly, and use a SQLite `TEXT` column if you need to store it as text. + +Await outstanding queries, dumps, and transactions before calling `orm.close()`. If close reports a busy connection, await the work and retry. diff --git a/packages/integrations/nitro-ui/mikro-orm/package.json b/packages/integrations/nitro-ui/mikro-orm/package.json new file mode 100644 index 00000000..f5e15351 --- /dev/null +++ b/packages/integrations/nitro-ui/mikro-orm/package.json @@ -0,0 +1,57 @@ +{ + "name": "nitro-sqlite-mikro-orm", + "version": "11.0.0", + "description": "MikroORM SQLite driver for NitroUI using Nitro SQLite.", + "source": "./src/index.ts", + "main": "./src/index.ts", + "types": "./src/index.ts", + "files": [ + "src", + "scripts", + "README.md", + "LICENSE", + "tsconfig.json" + ], + "scripts": { + "materialize": "node scripts/materialize.mjs", + "typecheck": "node scripts/materialize.mjs && tsc --noEmit", + "prepack": "node scripts/materialize.mjs && tsc --noEmit", + "prepublishOnly": "node scripts/materialize.mjs && tsc --noEmit", + "test": "node scripts/materialize.mjs && node --experimental-strip-types --test tests/*.test.ts", + "pack": "bun pm pack" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/margelo/nitro-sqlite.git" + }, + "author": "Christoph Pader", + "license": "MIT", + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "access": "public" + }, + "dependencies": { + "kysely-generic-sqlite": "^2.0.1", + "nitro-sqlite-kysely": "11.0.0" + }, + "peerDependencies": { + "@mikro-orm/sql": "~7.2.13", + "kysely": "^0.29.9", + "nitro-sqlite": ">=11.0.0-0" + }, + "devDependencies": { + "@mikro-orm/sql": "7.2.13", + "kysely": "0.29.9", + "nitro-sqlite": "11.0.0", + "better-sqlite3": "^12.11.1", + "@types/node": "^25.0.0", + "typescript": "^6.0.3" + }, + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./package.json": "./package.json" + } +} diff --git a/packages/integrations/nitro-ui/mikro-orm/scripts/materialize.mjs b/packages/integrations/nitro-ui/mikro-orm/scripts/materialize.mjs new file mode 100644 index 00000000..c81853d2 --- /dev/null +++ b/packages/integrations/nitro-ui/mikro-orm/scripts/materialize.mjs @@ -0,0 +1,19 @@ +import { existsSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const packageDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const sharedHelper = resolve( + packageDirectory, + '../../../../shared/orm/materialize-sources.mjs', +) +if (existsSync(sharedHelper)) { + const { materializeOrmSources } = await import( + pathToFileURL(sharedHelper).href + ) + materializeOrmSources(packageDirectory) +} else if (!existsSync(join(packageDirectory, 'src/index.ts'))) { + throw new Error( + 'ORM source is missing. Prepare the package from the workspace before packing it.', + ) +} diff --git a/packages/integrations/nitro-ui/mikro-orm/tests/connection.test.ts b/packages/integrations/nitro-ui/mikro-orm/tests/connection.test.ts new file mode 100644 index 00000000..7ad30013 --- /dev/null +++ b/packages/integrations/nitro-ui/mikro-orm/tests/connection.test.ts @@ -0,0 +1,22 @@ +import * as nodeModule from 'node:module' +import { registerBehaviorTests } from '../../../../../shared/orm/mikro-orm/tests/behavior.ts' +import { resolve } from './resolve.mjs' + +if (nodeModule.registerHooks) { + nodeModule.registerHooks({ resolve }) +} else { + nodeModule.register('./resolve.mjs', import.meta.url) +} + +const { open, resetAllDatabases } = await import( + '../../../../nitro-sqlite/src/mock.ts' +) +const { nativeHooks } = await import('./nativeMock.ts') +const { NitroSQLiteDriver } = await import('../src/index.ts') + +registerBehaviorTests({ + open, + resetAllDatabases, + nativeHooks, + NitroSQLiteDriver, +}) diff --git a/packages/integrations/nitro-ui/mikro-orm/tests/nativeMock.ts b/packages/integrations/nitro-ui/mikro-orm/tests/nativeMock.ts new file mode 100644 index 00000000..1d28b725 --- /dev/null +++ b/packages/integrations/nitro-ui/mikro-orm/tests/nativeMock.ts @@ -0,0 +1,25 @@ +import { open as openMock } from '../../../../nitro-sqlite/src/mock.ts' + +export const nativeHooks: { + beforeExecute?: ( + sql: string, + database: ReturnType, + ) => Promise | undefined + beforeClose?: () => void +} = {} + +export function open(options: Parameters[0]) { + const database = openMock(options) + const executeAsync: typeof database.executeAsync = async (sql, params) => { + await nativeHooks.beforeExecute?.(sql, database) + return database.executeAsync(sql, params) + } + return { + ...database, + executeAsync, + close: () => { + nativeHooks.beforeClose?.() + database.close() + }, + } +} diff --git a/packages/integrations/nitro-ui/mikro-orm/tests/resolve.mjs b/packages/integrations/nitro-ui/mikro-orm/tests/resolve.mjs new file mode 100644 index 00000000..c10b79f7 --- /dev/null +++ b/packages/integrations/nitro-ui/mikro-orm/tests/resolve.mjs @@ -0,0 +1,22 @@ +import { extname } from 'node:path' + +const packagesUrl = new URL('../../../../', import.meta.url).href + +// Resolve Metro-style imports to the workspace sources and replace the native entry point. +export function resolve(specifier, context, nextResolve) { + if (specifier === 'nitro-sqlite') { + return nextResolve( + new URL('./nativeMock.ts', import.meta.url).href, + context, + ) + } + if ( + context.parentURL?.startsWith(packagesUrl) && + !context.parentURL.includes('/node_modules/') && + (specifier.startsWith('./') || specifier.startsWith('../')) && + extname(specifier) === '' + ) { + return nextResolve(`${specifier}.ts`, context) + } + return nextResolve(specifier, context) +} diff --git a/packages/integrations/nitro-ui/mikro-orm/tsconfig.json b/packages/integrations/nitro-ui/mikro-orm/tsconfig.json new file mode 100644 index 00000000..961662b7 --- /dev/null +++ b/packages/integrations/nitro-ui/mikro-orm/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "target": "ESNext", + "lib": ["ESNext"], + "noUncheckedIndexedAccess": true, + "noImplicitReturns": true, + "types": [], + "paths": { + "nitro-sqlite": ["../../../nitro-sqlite/src/index.ts"], + "nitro-sqlite-kysely": ["../kysely/src/index.ts"] + } + }, + "include": ["src"] +} diff --git a/packages/integrations/nitro-ui/typeorm/.gitignore b/packages/integrations/nitro-ui/typeorm/.gitignore new file mode 100644 index 00000000..33129759 --- /dev/null +++ b/packages/integrations/nitro-ui/typeorm/.gitignore @@ -0,0 +1,2 @@ +*.tgz +node_modules diff --git a/packages/integrations/nitro-ui/typeorm/.npmignore b/packages/integrations/nitro-ui/typeorm/.npmignore new file mode 100644 index 00000000..320100c6 --- /dev/null +++ b/packages/integrations/nitro-ui/typeorm/.npmignore @@ -0,0 +1,2 @@ +tests/ +tsconfig.tsbuildinfo diff --git a/packages/integrations/nitro-ui/typeorm/LICENSE b/packages/integrations/nitro-ui/typeorm/LICENSE new file mode 100644 index 00000000..01aa59f2 --- /dev/null +++ b/packages/integrations/nitro-ui/typeorm/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2024 Marc Rousavy & Christoph Pader +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/integrations/nitro-ui/typeorm/README.md b/packages/integrations/nitro-ui/typeorm/README.md new file mode 100644 index 00000000..8d7ce182 --- /dev/null +++ b/packages/integrations/nitro-ui/typeorm/README.md @@ -0,0 +1,38 @@ +# nitro-sqlite-typeorm + +TypeORM maps entities to SQLite tables. This package connects TypeORM's `react-native` DataSource to Nitro SQLite's callback adapter on NitroUI. + +For this unpublished 11.0.0 pre-release, build and install local archives for the adapter and companion. See the [companion installation guide](../../../../docs/content/docs/integrations/orms/index.mdx) for packing steps and peer dependencies. + +Install the adapter and its peers in your NitroUI app: + +```sh +npm install /path/to/nitro-sqlite-typeorm-11.0.0.tgz /path/to/nitro-sqlite-11.0.0.tgz typeorm@1.1.2 +``` + +The adapter requires Nitro SQLite 11.0.0 or a compatible prerelease and TypeORM 1.1.2 or a compatible 1.x version. Configure TypeORM's browser build and module resolution as described in the [TypeORM integration guide](https://sqlite.margelo.com/docs/integrations/orms/typeorm). + +```ts +import { DataSource } from 'typeorm' +import { typeORMDriver } from 'nitro-sqlite-typeorm' + +const dataSource = new DataSource({ + type: 'react-native', + database: 'app.sqlite', + location: '.', + driver: typeORMDriver, + entities: [], +}) + +await dataSource.initialize() +// Use repositories and migrations through this DataSource. +await dataSource.destroy() +``` + +`typeORMDriver.openDatabase(options, ok, fail)` opens a database by `name`, optional relative `location`, and optional SEE `encryptionKey`. It calls `ok` and returns a `TypeOrmConnection` on success, or calls `fail` and returns `null` when opening fails. `TypeOrmNitroSQLiteConnection` names the same connection type for existing apps. + +Queries use asynchronous callbacks. Transactions use Nitro SQLite's managed transaction queue. Attach and detach run synchronously and throw on failure. Close reports failures through its callback. Opening and query failure callbacks preserve the caught error value, despite their legacy string type. A supplied encryption key requires a licensed SQLite SEE build. Without SEE, opening fails with `EncryptionNotEnabled`. + +Core's `typeORMDriver`, `TypeOrmConnection`, and `TypeOrmNitroSQLiteConnection` imports remain available but are deprecated. This package forwards to that single dependency-free implementation. Installing core alone does not install this package or TypeORM. Existing apps that keep the legacy import must install TypeORM explicitly. + +For Jest, mock `nitro-sqlite` before importing this adapter and provide its `typeORMDriver` export. The Node-only `nitro-sqlite/mock` entry point does not provide the callback adapter. diff --git a/packages/integrations/nitro-ui/typeorm/package.json b/packages/integrations/nitro-ui/typeorm/package.json new file mode 100644 index 00000000..19aa9679 --- /dev/null +++ b/packages/integrations/nitro-ui/typeorm/package.json @@ -0,0 +1,51 @@ +{ + "name": "nitro-sqlite-typeorm", + "version": "11.0.0", + "description": "TypeORM adapter for nitro-sqlite.", + "source": "./src/index.ts", + "main": "./src/index.ts", + "module": "./src/index.ts", + "types": "./src/index.ts", + "type": "module", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./package.json": "./package.json" + }, + "files": [ + "src", + "!**/__tests__", + "README.md", + "LICENSE" + ], + "scripts": { + "typecheck": "tsc --noEmit", + "prepack": "tsc --noEmit", + "prepublishOnly": "tsc --noEmit", + "pack": "bun pm pack", + "test": "bun test tests/package.test.ts" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/margelo/nitro-sqlite.git", + "directory": "packages/integrations/nitro-ui/typeorm" + }, + "author": "Christoph Pader", + "license": "MIT", + "homepage": "https://sqlite.margelo.com/docs/integrations/orms/typeorm", + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "access": "public" + }, + "peerDependencies": { + "nitro-sqlite": ">=11.0.0-0", + "typeorm": "^1.1.2" + }, + "devDependencies": { + "nitro-sqlite": "11.0.0", + "typeorm": "1.1.2", + "typescript": "^6.0.3" + } +} diff --git a/packages/integrations/nitro-ui/typeorm/src/index.ts b/packages/integrations/nitro-ui/typeorm/src/index.ts new file mode 100644 index 00000000..8349a2f2 --- /dev/null +++ b/packages/integrations/nitro-ui/typeorm/src/index.ts @@ -0,0 +1,35 @@ +import { + typeORMDriver as legacyDriver, + type TypeOrmConnection as LegacyConnection, +} from 'nitro-sqlite' + +/** + * Callback connection owned by a TypeORM `react-native` DataSource. + * Queries run asynchronously through `executeSql`; transactions use Nitro + * SQLite's managed transaction queue. Close the connection through + * `DataSource.destroy()` when the DataSource is no longer needed. + * + * Opening and query failure callbacks preserve the caught error value, even + * though the legacy callback signature declares a string. Close failures use + * the failure callback; attachment and detachment failures throw synchronously. + */ +export type TypeOrmConnection = LegacyConnection + +/** + * Compatibility name for {@link TypeOrmConnection} used by existing TypeORM apps. + * The connection has the same callbacks and lifecycle as `TypeOrmConnection`. + */ +export type TypeOrmNitroSQLiteConnection = TypeOrmConnection + +/** + * SQLite callback adapter for TypeORM's `react-native` DataSource type. + * Pass this object as the DataSource's `driver` option. `openDatabase` accepts + * a database `name`, optional relative `location`, and optional SEE + * `encryptionKey`. It calls `ok` and returns the connection on success, or + * calls `fail` and returns `null` when opening fails. + * + * This package shares the core adapter implementation, so legacy core imports + * and this entry point use the same connection lifecycle and callbacks. + * TypeORM and nitro-sqlite must be installed as peer dependencies. + */ +export const typeORMDriver = legacyDriver diff --git a/packages/integrations/nitro-ui/typeorm/tests/package.test.ts b/packages/integrations/nitro-ui/typeorm/tests/package.test.ts new file mode 100644 index 00000000..df0fd83d --- /dev/null +++ b/packages/integrations/nitro-ui/typeorm/tests/package.test.ts @@ -0,0 +1,116 @@ +import { afterAll, expect, test } from 'bun:test' +import { spawnSync } from 'node:child_process' +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const packageDirectory = fileURLToPath(new URL('..', import.meta.url)) +const hostName = 'nitro-sqlite' +const packageName = `${hostName}-typeorm` +const temporaryDirectory = mkdtempSync( + join(tmpdir(), `${packageName}-consumer-`), +) +const manifest = JSON.parse( + readFileSync(join(packageDirectory, 'package.json'), 'utf8'), +) + +afterAll(() => rmSync(temporaryDirectory, { recursive: true, force: true })) + +test('requires explicit TypeORM and host peers without pulling TypeORM into core', () => { + expect(manifest.peerDependencies).toEqual({ + [hostName]: '>=11.0.0-0', + typeorm: '^1.1.2', + }) + expect(manifest.dependencies?.typeorm).toBeUndefined() + const hostManifest = JSON.parse( + readFileSync( + join(packageDirectory, '../../..', hostName, 'package.json'), + 'utf8', + ), + ) + expect(hostManifest.dependencies?.typeorm).toBeUndefined() + expect(hostManifest.peerDependencies?.typeorm).toBeUndefined() + expect(hostManifest.optionalDependencies?.typeorm).toBeUndefined() +}) + +test('packed entry point imports without TypeORM and preserves the host driver object', async () => { + const packed = spawnSync( + 'bun', + ['run', 'pack', '--destination', temporaryDirectory], + { + cwd: packageDirectory, + encoding: 'utf8', + }, + ) + if (packed.status !== 0) { + throw new Error( + `Package failed to pack:\n${packed.stdout}\n${packed.stderr}`, + ) + } + const archive = readdirSync(temporaryDirectory).find((file) => + file.endsWith('.tgz'), + ) + if (!archive) throw new Error('Package command did not produce an archive') + const unpacked = spawnSync( + 'tar', + ['-xzf', join(temporaryDirectory, archive), '-C', temporaryDirectory], + { + encoding: 'utf8', + }, + ) + if (unpacked.status !== 0) throw new Error(unpacked.stderr) + const packedDirectory = join(temporaryDirectory, 'package') + const packedManifest = JSON.parse( + readFileSync(join(packedDirectory, 'package.json'), 'utf8'), + ) + expect(packedManifest.name).toBe(packageName) + expect(existsSync(join(packedDirectory, 'LICENSE'))).toBe(true) + expect(existsSync(join(packedDirectory, 'tests'))).toBe(false) + expect(existsSync(join(temporaryDirectory, 'node_modules', 'typeorm'))).toBe( + false, + ) + for (const field of ['main', 'module', 'types']) { + expect(packedManifest[field].startsWith('./')).toBe(true) + expect(existsSync(join(packedDirectory, packedManifest[field]))).toBe(true) + } + for (const target of Object.values(packedManifest.exports['.'])) { + if (typeof target !== 'string') + throw new Error('Export target must be a relative file') + expect(target.startsWith('./')).toBe(true) + expect(existsSync(join(packedDirectory, target))).toBe(true) + } + + // Native bindings cannot run in this package-only consumer. A host fixture + // checks standard package resolution and object identity without TypeORM. + const hostDirectory = join(temporaryDirectory, 'node_modules', hostName) + mkdirSync(hostDirectory, { recursive: true }) + writeFileSync( + join(hostDirectory, 'package.json'), + JSON.stringify({ + name: hostName, + type: 'module', + exports: { '.': './index.js' }, + }), + ) + writeFileSync( + join(hostDirectory, 'index.js'), + 'export const typeORMDriver = { openDatabase: () => null }', + ) + const { typeORMDriver: driver } = await import( + pathToFileURL(join(hostDirectory, 'index.js')).href + ) + const entrypoint = pathToFileURL( + join(packedDirectory, packedManifest.exports['.'].default), + ) + const adapter = await import(entrypoint.href) + expect(adapter.typeORMDriver).toBe(driver) +}) diff --git a/packages/integrations/nitro-ui/typeorm/tsconfig.json b/packages/integrations/nitro-ui/typeorm/tsconfig.json new file mode 100644 index 00000000..d6a1eb7d --- /dev/null +++ b/packages/integrations/nitro-ui/typeorm/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "target": "ESNext", + "lib": ["ESNext"], + "noUncheckedIndexedAccess": true, + "noImplicitReturns": true, + "experimentalDecorators": true, + "types": [], + "paths": { + "nitro-sqlite": ["../../../nitro-sqlite/src/index.ts"] + } + }, + "include": ["src"] +} diff --git a/packages/integrations/nitro-ui/vec/.gitignore b/packages/integrations/nitro-ui/vec/.gitignore new file mode 100644 index 00000000..be49c040 --- /dev/null +++ b/packages/integrations/nitro-ui/vec/.gitignore @@ -0,0 +1,5 @@ +/src/helpers.ts +/cpp/vendor/ +/nitrogen/generated/ +.build/ +.swiftpm/ diff --git a/packages/integrations/nitro-ui/vec/LICENSE b/packages/integrations/nitro-ui/vec/LICENSE new file mode 100644 index 00000000..01aa59f2 --- /dev/null +++ b/packages/integrations/nitro-ui/vec/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2024 Marc Rousavy & Christoph Pader +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/integrations/nitro-ui/vec/Package.swift b/packages/integrations/nitro-ui/vec/Package.swift new file mode 100644 index 00000000..fbdcb2f8 --- /dev/null +++ b/packages/integrations/nitro-ui/vec/Package.swift @@ -0,0 +1,37 @@ +// swift-tools-version: 6.4 +import PackageDescription + +let core: Target.Dependency = .product(name: "NitroModules", package: "nitro-core") +let sqlite: Target.Dependency = .product(name: "NitroSQLite", package: "app-nitrosqlite") +let flags: [CXXSetting] = [ + .headerSearchPath("cpp"), + .headerSearchPath("cpp/vendor"), + .headerSearchPath("cpp/vendor/sqlite"), + .define("SQLITE_CORE", to: "1"), + .define("SQLITE_VEC_STATIC", to: "1"), +] + +// NitroUI CLI aliases native modules by module name in .nitro/native. +let package = Package( + name: "NitroSQLiteVec", + platforms: [.iOS(.v16)], + products: [.library(name: "NitroSQLiteVec", targets: ["NitroSQLiteVec", "NitroSQLiteVecRegistration"])], + dependencies: [.package(path: "../nitro-core"), .package(path: "../app-nitrosqlite")], + targets: [ + .target( + name: "NitroSQLiteVec", dependencies: [core, sqlite], path: ".", + sources: ["cpp", "nitrogen/generated/shared/c++"], + resources: [.copy("ios/PrivacyInfo.xcprivacy")], + publicHeadersPath: "nitrogen/generated/shared/c++/include", + cSettings: [.headerSearchPath("cpp/vendor/sqlite"), .define("SQLITE_CORE", to: "1"), .define("SQLITE_VEC_STATIC", to: "1")], + cxxSettings: flags + ), + .target( + name: "NitroSQLiteVecRegistration", dependencies: ["NitroSQLiteVec", core], + path: "nitrogen/generated/apple", sources: ["c++", "NitroSQLiteVecAutolinking.cpp"], + publicHeadersPath: "c++/include", + cxxSettings: [.headerSearchPath("../../../cpp")] + ), + ], + cxxLanguageStandard: .cxx20 +) diff --git a/packages/integrations/nitro-ui/vec/README.md b/packages/integrations/nitro-ui/vec/README.md new file mode 100644 index 00000000..a82d6331 --- /dev/null +++ b/packages/integrations/nitro-ui/vec/README.md @@ -0,0 +1,47 @@ +# nitro-sqlite-vec + +Opt-in [sqlite-vec](https://github.com/asg017/sqlite-vec) vector search for `nitro-sqlite` on NitroUI iOS and Android. The extension links to the adapter's single SQLite engine. It does not load native extensions at runtime or bundle another SQLite engine. + +For this unpublished 11.0.0 pre-release, build and install local archives for the adapter and companion. See the [companion installation guide](../../../../docs/content/docs/integrations/orms/index.mdx) for packing steps and peer dependencies. + +## Installation + +Install the local archives for `nitro-sqlite` and `nitro-sqlite-vec` as direct app dependencies, then prepare and rebuild the native app with the NitroUI CLI. Both packages must be direct dependencies because the pinned CLI discovers app modules from direct dependencies. + +```sh +bun add /path/to/nitro-sqlite-11.0.0.tgz /path/to/nitro-sqlite-vec-11.0.0.tgz +``` + +This pre-release package targets NitroUI SDK 0.2.0 and its matching Nitro Core runtime. It is separate from `react-native-nitro-sqlite-vec`, which remains the React Native companion. + +## Register before opening connections + +SQLite extensions add functions and virtual table modules to database connections. This package registers sqlite-vec as an automatic extension for future connections. Register once during app startup before opening databases. Repeated registration is safe; existing connections are unchanged. + +```ts +import { open } from 'nitro-sqlite' +import { + registerVectorExtensions, + vecVersion, + createVectorTable, + knnSearch, +} from 'nitro-sqlite-vec' + +registerVectorExtensions() +const db = open({ name: 'vectors.sqlite' }) +try { + console.log(vecVersion(db)) + createVectorTable(db, 'embeddings', { dimensions: 3 }) + db.execute('INSERT INTO embeddings (rowid, embedding) VALUES (?, ?)', [1, '[0.1,0.2,0.3]']) + const matches = knnSearch(db, 'embeddings', [0.1, 0.2, 0.25], 10) + console.log(matches) +} finally { + db.close() +} +``` + +The companion also exports `isVecAvailable`, `VectorColumnType`, `VectorDistanceMetric`, `CreateVectorTableOptions`, `KnnSearchOptions`, and `KnnMatch`. Its query helpers share the React Native companion's implementation. Table and column names are trusted SQL identifiers, so do not pass user input as identifiers. Query values use parameters. + +## Package contents + +Package builds copy the shared sqlite-vec source, query helpers, and matching core SQLite headers into the archive and generate Nitro bindings. Installed archives include these inputs and do not need this repository or an example app. The iOS manifest uses the native package aliases supplied by the NitroUI CLI; Android links the discovered `NitroSQLite` target. The included privacy manifest declares no tracking or data collection by this extension. See `THIRD_PARTY_NOTICES.md` for bundled source licenses. diff --git a/packages/integrations/nitro-ui/vec/THIRD_PARTY_NOTICES.md b/packages/integrations/nitro-ui/vec/THIRD_PARTY_NOTICES.md new file mode 100644 index 00000000..8454591d --- /dev/null +++ b/packages/integrations/nitro-ui/vec/THIRD_PARTY_NOTICES.md @@ -0,0 +1,31 @@ +# Third-party notices + +## sqlite-vec + +`cpp/vendor/sqlite-vec` contains sqlite-vec v0.1.9, shared with the React Native companion. sqlite-vec is dual-licensed under MIT and Apache 2.0; this package uses its MIT license. Source: https://github.com/asg017/sqlite-vec/tree/v0.1.9. + +MIT License + +Copyright (c) 2024 Alex Garcia + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## SQLite + +`cpp/vendor/sqlite` contains headers from the core adapter's SQLite build, including its private symbol prefixes. SQLite is in the public domain: https://sqlite.org/copyright.html. No SQLite engine implementation is included in this package; the adapter supplies it. diff --git a/packages/integrations/nitro-ui/vec/android/nitro-ui.cmake b/packages/integrations/nitro-ui/vec/android/nitro-ui.cmake new file mode 100644 index 00000000..7e79efb7 --- /dev/null +++ b/packages/integrations/nitro-ui/vec/android/nitro-ui.cmake @@ -0,0 +1,11 @@ +# Compile the extension against the adapter's headers and its single SQLite engine. +get_filename_component(NITRO_SQLITE_VEC_MODULE_ROOT "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE) +target_sources(NitroSQLiteVec PRIVATE "${NITRO_SQLITE_VEC_MODULE_ROOT}/cpp/vendor/sqlite-vec/sqlite-vec.c") +target_include_directories(NitroSQLiteVec PRIVATE + "${NITRO_SQLITE_VEC_MODULE_ROOT}/cpp/vendor/sqlite" + "${NITRO_SQLITE_VEC_MODULE_ROOT}/cpp/vendor" +) +target_compile_definitions(NitroSQLiteVec PRIVATE SQLITE_CORE=1 SQLITE_VEC_STATIC=1) +target_compile_features(NitroSQLiteVec PUBLIC cxx_std_20) +target_link_libraries(NitroSQLiteVec NitroSQLite) +set_target_properties(NitroSQLiteVec PROPERTIES POSITION_INDEPENDENT_CODE ON) diff --git a/packages/integrations/nitro-ui/vec/cpp/HybridSQLiteVec.cpp b/packages/integrations/nitro-ui/vec/cpp/HybridSQLiteVec.cpp new file mode 100644 index 00000000..56d5f048 --- /dev/null +++ b/packages/integrations/nitro-ui/vec/cpp/HybridSQLiteVec.cpp @@ -0,0 +1,10 @@ +#include "HybridSQLiteVec.hpp" +#include "vendor/SQLiteVecRegisterVectorExtensions.hpp" + +namespace margelo::nitro::nitrosqlitevec { + +void HybridSQLiteVec::enable() { + ::margelo::nitrosqlitevec::registerVectorExtensions(); +} + +} // namespace margelo::nitro::nitrosqlitevec diff --git a/packages/integrations/nitro-ui/vec/cpp/HybridSQLiteVec.hpp b/packages/integrations/nitro-ui/vec/cpp/HybridSQLiteVec.hpp new file mode 100644 index 00000000..36ffa042 --- /dev/null +++ b/packages/integrations/nitro-ui/vec/cpp/HybridSQLiteVec.hpp @@ -0,0 +1,15 @@ +#pragma once + +#include + +namespace margelo::nitro::nitrosqlitevec { + +/** Registers the companion extension with the adapter's single SQLite engine. */ +class HybridSQLiteVec final : public HybridSQLiteVecSpec { +public: + HybridSQLiteVec() = default; + /** Enable sqlite-vec for connections created after this call. */ + void enable() override; +}; + +} // namespace margelo::nitro::nitrosqlitevec diff --git a/packages/integrations/nitro-ui/vec/ios/PrivacyInfo.xcprivacy b/packages/integrations/nitro-ui/vec/ios/PrivacyInfo.xcprivacy new file mode 100644 index 00000000..8a9617d0 --- /dev/null +++ b/packages/integrations/nitro-ui/vec/ios/PrivacyInfo.xcprivacy @@ -0,0 +1,14 @@ + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + NSPrivacyAccessedAPITypes + + + diff --git a/packages/integrations/nitro-ui/vec/nitro.json b/packages/integrations/nitro-ui/vec/nitro.json new file mode 100644 index 00000000..4e969abe --- /dev/null +++ b/packages/integrations/nitro-ui/vec/nitro.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://nitro.margelo.com/nitro.schema.json", + "environment": "bare", + "cxxNamespace": ["nitrosqlitevec"], + "apple": { + "moduleName": "NitroSQLiteVec" + }, + "android": { + "namespace": ["nitrosqlitevec"], + "cxxLibName": "NitroSQLiteVec" + }, + "ignorePaths": ["**/node_modules", "**/.build", "**/.swiftpm"] +} diff --git a/packages/integrations/nitro-ui/vec/package.json b/packages/integrations/nitro-ui/vec/package.json new file mode 100644 index 00000000..6d84fecf --- /dev/null +++ b/packages/integrations/nitro-ui/vec/package.json @@ -0,0 +1,68 @@ +{ + "name": "nitro-sqlite-vec", + "version": "11.0.0", + "description": "Opt-in sqlite-vec vector search for NitroUI SQLite, sharing its single SQLite engine.", + "license": "MIT", + "author": "Christoph Pader", + "type": "module", + "module": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./package.json": "./package.json" + }, + "imports": { + "#nitro/*": "./nitrogen/generated/shared/javascript/*.cjs" + }, + "files": [ + "src", + "cpp", + "android", + "ios", + "nitrogen", + "scripts/materialize.mjs", + "Package.swift", + "nitro.json", + "tsconfig.json", + "THIRD_PARTY_NOTICES.md", + "README.md", + "LICENSE" + ], + "scripts": { + "materialize": "node scripts/materialize.mjs", + "specs": "node scripts/materialize.mjs && nitrogen", + "typecheck": "node scripts/materialize.mjs && nitrogen && tsc --noEmit", + "build": "node scripts/materialize.mjs && nitrogen && tsc --noEmit", + "prepack": "node scripts/materialize.mjs && nitrogen && tsc --noEmit", + "prepublishOnly": "node scripts/materialize.mjs && nitrogen && tsc --noEmit", + "pack": "bun pm pack", + "test:materialize": "node scripts/materialize.mjs && node --test scripts/materialize.test.mjs" + }, + "dependencies": { + "nitro-core": "1.0.0-alpha.nightly.137.gd4793c40b8b8" + }, + "peerDependencies": { + "nitro-sqlite": ">=11.0.0-0" + }, + "devDependencies": { + "nitrogen": "1.0.0-alpha.nightly.137.gd4793c40b8b8", + "typescript": "^6.0.3" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/margelo/nitro-sqlite.git", + "directory": "packages/integrations/nitro-ui/vec" + }, + "homepage": "https://sqlite.margelo.com", + "bugs": { + "url": "https://github.com/margelo/nitro-sqlite/issues" + }, + "publishConfig": { + "access": "public", + "tag": "next", + "registry": "https://registry.npmjs.org/" + } +} diff --git a/packages/integrations/nitro-ui/vec/scripts/materialize.mjs b/packages/integrations/nitro-ui/vec/scripts/materialize.mjs new file mode 100644 index 00000000..2f48cb4e --- /dev/null +++ b/packages/integrations/nitro-ui/vec/scripts/materialize.mjs @@ -0,0 +1,50 @@ +import { existsSync, readFileSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const packageDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const vectorDirectory = process.env.NITRO_SQLITE_VEC_SOURCE_ROOT + ? resolve(process.env.NITRO_SQLITE_VEC_SOURCE_ROOT) + : resolve(packageDirectory, '../../react-native/vec') +const sqliteDirectory = process.env.NITRO_SQLITE_SOURCE_ROOT + ? resolve(process.env.NITRO_SQLITE_SOURCE_ROOT) + : resolve(packageDirectory, '../../../nitro-sqlite-core') +const files = [ + ['src/helpers.ts', join(vectorDirectory, 'src/index.ts')], + ...[ + 'SQLiteVecRegisterVectorExtensions.cpp', + 'SQLiteVecRegisterVectorExtensions.hpp', + 'sqlite-vec/sqlite-vec.c', + 'sqlite-vec/sqlite-vec.h', + ].map((file) => [`cpp/vendor/${file}`, join(vectorDirectory, 'cpp', file)]), + ...['sqlite3.h', 'sqlite3-symbol-prefix.h'].map((file) => [ + `cpp/vendor/sqlite/${file}`, + join(sqliteDirectory, 'cpp/sqlite', file), + ]), +] + +if (existsSync(vectorDirectory) && existsSync(sqliteDirectory)) { + const { writeGeneratedFile } = await import( + '../../../../nitro-sqlite-core/scripts/materialize-sources.mjs' + ) + // Read every input first, so an incomplete checkout cannot partially replace a package. + const sources = files.map(([destination, source]) => [ + destination, + destination === 'src/helpers.ts' + ? Buffer.from( + readFileSync(source, 'utf8').replaceAll( + "'react-native-nitro-sqlite'", + "'nitro-sqlite'", + ), + ) + : readFileSync(source), + ]) + for (const [file, content] of sources) { + const destination = join(packageDirectory, file) + writeGeneratedFile(destination, content) + } +} else if (!files.every(([file]) => existsSync(join(packageDirectory, file)))) { + throw new Error( + 'Missing sqlite-vec sources. Build from the workspace or use a complete package archive.', + ) +} diff --git a/packages/integrations/nitro-ui/vec/scripts/materialize.test.mjs b/packages/integrations/nitro-ui/vec/scripts/materialize.test.mjs new file mode 100644 index 00000000..321a111f --- /dev/null +++ b/packages/integrations/nitro-ui/vec/scripts/materialize.test.mjs @@ -0,0 +1,64 @@ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { + cpSync, + existsSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { test } from 'node:test' + +const source = resolve(dirname(fileURLToPath(import.meta.url)), '..') + +test('materializes shared helpers and prefixed headers without another SQLite engine', () => { + const result = run(source) + assert.equal(result.status, 0, result.stderr) + const helpers = readFileSync(join(source, 'src/helpers.ts'), 'utf8') + assert.ok(helpers.includes("from 'nitro-sqlite'")) + assert.ok(!helpers.includes("from 'react-native-nitro-sqlite'")) + assert.ok( + readFileSync(join(source, 'cpp/vendor/sqlite/sqlite3.h'), 'utf8').includes( + 'sqlite3-symbol-prefix.h', + ), + ) + assert.equal(existsSync(join(source, 'cpp/vendor/sqlite/sqlite3.c')), false) + const before = statSync(join(source, 'src/helpers.ts'), { bigint: true }) + assert.equal(run(source).status, 0) + assert.equal( + statSync(join(source, 'src/helpers.ts'), { bigint: true }).mtimeNs, + before.mtimeNs, + ) +}) + +test('complete archives work without sibling sources and incomplete archives fail', (context) => { + const directory = mkdtempSync(join(tmpdir(), 'nitro-sqlite-vec-archive-')) + context.after(() => rmSync(directory, { recursive: true, force: true })) + for (const entry of ['scripts', 'src', 'cpp']) { + cpSync(join(source, entry), join(directory, entry), { recursive: true }) + } + assert.equal(run(directory).status, 0) + rmSync(join(directory, 'cpp/vendor/sqlite/sqlite3-symbol-prefix.h')) + const incomplete = run(directory) + assert.notEqual(incomplete.status, 0) + assert.match(incomplete.stderr, /complete package archive/) +}) + +function run(directory) { + return spawnSync( + process.execPath, + [join(directory, 'scripts/materialize.mjs')], + { + encoding: 'utf8', + env: { + ...process.env, + NITRO_SQLITE_VEC_SOURCE_ROOT: '', + NITRO_SQLITE_SOURCE_ROOT: '', + }, + }, + ) +} diff --git a/packages/integrations/nitro-ui/vec/src/SQLiteVec.nitro.ts b/packages/integrations/nitro-ui/vec/src/SQLiteVec.nitro.ts new file mode 100644 index 00000000..7e9712e0 --- /dev/null +++ b/packages/integrations/nitro-ui/vec/src/SQLiteVec.nitro.ts @@ -0,0 +1,27 @@ +import { Android, iOS, type HybridObject } from 'nitro-core' + +export * from '#nitro/SQLiteVec' + +/** Registers sqlite-vec against the NitroUI SQLite adapter's single engine. */ +@iOS({ + language: 'c++', + implementation: { + className: 'HybridSQLiteVec', + include: '"HybridSQLiteVec.hpp"', + }, +}) +@Android({ + language: 'c++', + implementation: { + className: 'HybridSQLiteVec', + include: '"HybridSQLiteVec.hpp"', + }, +}) +export declare class SQLiteVec extends HybridObject { + /** Create a registration service. Constructing it does not enable the extension. */ + constructor() + /** Register sqlite-vec functions and vec0 for connections opened after this call. + * Existing connections are unchanged. Repeated calls are safe and process-wide. + * @throws If native registration fails. */ + enable(): void +} diff --git a/packages/integrations/nitro-ui/vec/src/index.ts b/packages/integrations/nitro-ui/vec/src/index.ts new file mode 100644 index 00000000..0fb873db --- /dev/null +++ b/packages/integrations/nitro-ui/vec/src/index.ts @@ -0,0 +1,13 @@ +import { SQLiteVec } from './SQLiteVec.nitro' + +export * from './helpers' + +/** + * Enable sqlite-vec functions and vec0 on connections opened after this call. + * Call before opening databases. Registration lasts for the process lifetime; + * repeated calls are safe. Existing connections are unchanged. + * @throws If native extension registration fails. + */ +export function registerVectorExtensions(): void { + new SQLiteVec().enable() +} diff --git a/packages/integrations/nitro-ui/vec/tsconfig.json b/packages/integrations/nitro-ui/vec/tsconfig.json new file mode 100644 index 00000000..efae2820 --- /dev/null +++ b/packages/integrations/nitro-ui/vec/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "target": "ESNext", + "lib": ["ESNext"], + "experimentalDecorators": true, + "noUncheckedIndexedAccess": true, + "noImplicitReturns": true, + "types": [] + }, + "include": ["src"], + "exclude": ["src/__tests__", "src/__mocks__"] +} diff --git a/packages/nitro-sqlite/package.json b/packages/nitro-sqlite/package.json index e10c9270..0f4a00e5 100644 --- a/packages/nitro-sqlite/package.json +++ b/packages/nitro-sqlite/package.json @@ -40,6 +40,7 @@ "test:materialize": "node scripts/materialize.mjs && node --test scripts/materialize.test.mjs", "build": "node scripts/materialize.mjs && nitrogen && tsc --noEmit", "prepack": "node scripts/materialize.mjs && nitrogen && tsc --noEmit", + "prepublishOnly": "node scripts/materialize.mjs && nitrogen && tsc --noEmit", "pack": "bun pm pack" }, "dependencies": { diff --git a/release-please-config.json b/release-please-config.json index 208bebaa..3f070ca4 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -139,6 +139,56 @@ "type": "json", "path": "examples/react-native/macos/package.json", "jsonpath": "$.dependencies['react-native-nitro-sqlite-typeorm']" + }, + { + "type": "json", + "path": "packages/nitro-sqlite/package.json", + "jsonpath": "$.version" + }, + { + "type": "json", + "path": "packages/integrations/nitro-ui/vec/package.json", + "jsonpath": "$.version" + }, + { + "type": "json", + "path": "packages/integrations/nitro-ui/drizzle/package.json", + "jsonpath": "$.version" + }, + { + "type": "json", + "path": "packages/integrations/nitro-ui/kysely/package.json", + "jsonpath": "$.version" + }, + { + "type": "json", + "path": "packages/integrations/nitro-ui/kysely/package.json", + "jsonpath": "$.devDependencies['nitro-sqlite']" + }, + { + "type": "json", + "path": "packages/integrations/nitro-ui/mikro-orm/package.json", + "jsonpath": "$.version" + }, + { + "type": "json", + "path": "packages/integrations/nitro-ui/mikro-orm/package.json", + "jsonpath": "$.dependencies['nitro-sqlite-kysely']" + }, + { + "type": "json", + "path": "packages/integrations/nitro-ui/mikro-orm/package.json", + "jsonpath": "$.devDependencies['nitro-sqlite']" + }, + { + "type": "json", + "path": "packages/integrations/nitro-ui/typeorm/package.json", + "jsonpath": "$.version" + }, + { + "type": "json", + "path": "packages/integrations/nitro-ui/typeorm/package.json", + "jsonpath": "$.devDependencies['nitro-sqlite']" } ] } diff --git a/scripts/companion-materialize.test.mjs b/scripts/companion-materialize.test.mjs new file mode 100644 index 00000000..e47a56d6 --- /dev/null +++ b/scripts/companion-materialize.test.mjs @@ -0,0 +1,107 @@ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { + chmodSync, + cpSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' +import test from 'node:test' + +const repository = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const packages = ['react-native', 'nitro-ui'].flatMap((host) => + [ + 'kysely', + 'mikro-orm', + 'drizzle', + ...(host === 'nitro-ui' ? ['vec'] : []), + ].map((name) => `packages/integrations/${host}/${name}`), +) + +for (const packagePath of packages) { + test(`${packagePath} bounds generated modes and remains standalone`, (context) => { + const root = mkdtempSync(join(tmpdir(), 'sqlite-companion-modes-')) + context.after(() => rmSync(root, { recursive: true, force: true })) + for (const path of [ + 'shared/orm', + 'packages/nitro-sqlite-core/scripts', + 'packages/nitro-sqlite-core/cpp/sqlite', + 'packages/nitro-sqlite-drizzle-core/src', + 'packages/integrations/react-native/vec/src', + 'packages/integrations/react-native/vec/cpp', + ]) { + cpSync(join(repository, path), join(root, path), { recursive: true }) + } + const directory = join(root, packagePath) + cpSync( + join(repository, packagePath, 'scripts'), + join(directory, 'scripts'), + { + recursive: true, + }, + ) + cpSync( + join(repository, packagePath, 'package.json'), + join(directory, 'package.json'), + ) + const generated = join( + directory, + packagePath.endsWith('/vec') ? 'src/helpers.ts' : 'src/index.ts', + ) + run(directory, 0o077) + assert.equal(statSync(generated).mode & 0o777, 0o600) + const content = readFileSync(generated) + chmodSync(generated, 0o666) + const modified = statSync(generated).mtimeMs + run(directory, 0o022) + assert.equal(statSync(generated).mode & 0o777, 0o644) + assert.equal(statSync(generated).mtimeMs, modified) + chmodSync(generated, 0o400) + run(directory, 0o022) + assert.equal(statSync(generated).mode & 0o777, 0o400) + chmodSync(generated, 0o600) + writeFileSync(generated, 'stale generated content') + chmodSync(generated, 0o400) + run(directory, 0o022) + assert.equal(statSync(generated).mode & 0o777, 0o400) + assert.deepEqual(readFileSync(generated), content) + rmSync(join(root, 'shared'), { recursive: true }) + rmSync(join(root, 'packages/nitro-sqlite-core'), { recursive: true }) + rmSync(join(root, 'packages/nitro-sqlite-drizzle-core'), { + recursive: true, + }) + if (packagePath.endsWith('/vec')) { + rmSync(join(root, 'packages/integrations/react-native/vec'), { + recursive: true, + }) + } + run(directory, 0o022) + assert.deepEqual(readFileSync(generated), content) + }) +} + +function run(directory, mask) { + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + `process.umask(${mask}); await import(${JSON.stringify(pathToFileURL(join(directory, 'scripts/materialize.mjs')).href)})`, + ], + { + encoding: 'utf8', + env: { + ...process.env, + NITRO_SQLITE_VEC_SOURCE_ROOT: '', + NITRO_SQLITE_SOURCE_ROOT: '', + }, + }, + ) + assert.equal(result.status, 0, result.stderr) +} diff --git a/scripts/prepare-workspace-sources.mjs b/scripts/prepare-workspace-sources.mjs index 7709fc8e..4ce67df5 100644 --- a/scripts/prepare-workspace-sources.mjs +++ b/scripts/prepare-workspace-sources.mjs @@ -1,5 +1,9 @@ import '../packages/react-native-nitro-sqlite/scripts/prepare-sources.mjs' import '../packages/nitro-sqlite/scripts/materialize.mjs' +import '../packages/integrations/nitro-ui/vec/scripts/materialize.mjs' import '../packages/integrations/react-native/drizzle/scripts/materialize.mjs' +import '../packages/integrations/nitro-ui/drizzle/scripts/materialize.mjs' import '../packages/integrations/react-native/kysely/scripts/materialize.mjs' +import '../packages/integrations/nitro-ui/kysely/scripts/materialize.mjs' import '../packages/integrations/react-native/mikro-orm/scripts/materialize.mjs' +import '../packages/integrations/nitro-ui/mikro-orm/scripts/materialize.mjs' diff --git a/scripts/publish-release.test.ts b/scripts/publish-release.test.ts index 6043fff3..4bce4446 100644 --- a/scripts/publish-release.test.ts +++ b/scripts/publish-release.test.ts @@ -13,36 +13,61 @@ import { test } from 'node:test' import { fileURLToPath } from 'node:url' const script = fileURLToPath(new URL('./publish-release.ts', import.meta.url)) +const reactNativePackages = [ + 'react-native-nitro-sqlite', + 'react-native-nitro-sqlite-vec', + 'react-native-nitro-sqlite-drizzle', + 'react-native-nitro-sqlite-kysely', + 'react-native-nitro-sqlite-mikro-orm', + 'react-native-nitro-sqlite-typeorm', +] +const nitroUIPackages = [ + 'nitro-sqlite', + 'nitro-sqlite-vec', + 'nitro-sqlite-drizzle', + 'nitro-sqlite-kysely', + 'nitro-sqlite-mikro-orm', + 'nitro-sqlite-typeorm', +] +const releasePackages = [...reactNativePackages, ...nitroUIPackages] test('publishing validates all packages and publishers before publishing in dependency order', () => { const result = runPublication() assert.equal(result.status, 0, result.stderr) const publish = result.calls.findIndex((line) => line.startsWith('npm:')) assert.ok(publish > 0) - for (const name of [ - 'react-native-nitro-sqlite', - 'react-native-nitro-sqlite-vec', - 'react-native-nitro-sqlite-drizzle', - 'react-native-nitro-sqlite-kysely', - 'react-native-nitro-sqlite-mikro-orm', - 'react-native-nitro-sqlite-typeorm', - ]) { - const preflight = result.calls.slice(0, publish) - assert.ok(preflight.includes(`bun:${name}:run typecheck`)) - assert.ok(preflight.includes(`bun:${name}:run lint`)) - assert.ok(preflight.includes(`bun:${name}:run prepublishOnly`)) - assert.ok(preflight.includes(`trusted:${name}`)) + const preflight = result.calls.slice(0, publish) + for (const name of releasePackages) { + assert.ok(preflight.includes(`bun:${name}:run typecheck`), name) + assert.ok(preflight.includes(`bun:${name}:run prepublishOnly`), name) + assert.ok(preflight.includes(`trusted:${name}`), name) } + for (const name of reactNativePackages) + assert.ok(preflight.includes(`bun:${name}:run lint`), name) + for (const name of nitroUIPackages) + assert.ok(!preflight.includes(`bun:${name}:run lint`), name) assert.deepEqual( result.calls.filter((line) => line.startsWith('npm:')), - [ - 'npm:react-native-nitro-sqlite:publish --access public --provenance --tag latest --workspaces=false --ignore-scripts', - 'npm:react-native-nitro-sqlite-vec:publish --access public --provenance --tag latest --workspaces=false --ignore-scripts', - 'npm:react-native-nitro-sqlite-drizzle:publish --access public --provenance --tag latest --workspaces=false --ignore-scripts', - 'npm:react-native-nitro-sqlite-kysely:publish --access public --provenance --tag latest --workspaces=false --ignore-scripts', - 'npm:react-native-nitro-sqlite-mikro-orm:publish --access public --provenance --tag latest --workspaces=false --ignore-scripts', - 'npm:react-native-nitro-sqlite-typeorm:publish --access public --provenance --tag latest --workspaces=false --ignore-scripts', - ], + releasePackages.map( + (name) => + `npm:${name}:publish --access public --provenance --tag latest --workspaces=false --ignore-scripts`, + ), + ) +}) + +test('a prerelease publishes every package to its channel tag', () => { + const result = runPublication({}, '11.0.0-alpha.0') + assert.equal(result.status, 0, result.stderr) + assert.deepEqual( + result.calls + .filter((line) => line.startsWith('npm:')) + .map((line) => line.split(':')[1]), + releasePackages, + ) + assert.ok( + result.calls + .filter((line) => line.startsWith('npm:')) + .every((line) => line.includes(' --tag alpha ')), ) }) @@ -60,6 +85,7 @@ test('a failed TypeORM prepublish build prevents every npm upload', () => { for (const name of [ 'react-native-nitro-sqlite-vec', 'react-native-nitro-sqlite-typeorm', + 'nitro-sqlite', ]) { test(`${name} validation failure prevents publishing any package`, () => { const result = runPublication({ PUBLISH_TEST_FAIL_VALIDATION: name }) @@ -75,6 +101,7 @@ for (const name of [ for (const name of [ 'react-native-nitro-sqlite-mikro-orm', 'react-native-nitro-sqlite-typeorm', + 'nitro-sqlite-typeorm', ]) { test(`${name} trusted publisher failure prevents publishing any package`, () => { const result = runPublication({ PUBLISH_TEST_FAIL_OIDC: name }) @@ -93,13 +120,12 @@ test('retry skips a package already published from the selected commit', () => { PUBLISH_TEST_EXISTING_PACKAGE: 'react-native-nitro-sqlite', }) assert.equal(result.status, 0, result.stderr) - const published = result.calls.filter((line) => line.startsWith('npm:')) - assert.equal(published.length, 5) - assert.match(published[0]!, /^npm:react-native-nitro-sqlite-vec:/) - assert.match(published[1]!, /^npm:react-native-nitro-sqlite-drizzle:/) - assert.match(published[2]!, /^npm:react-native-nitro-sqlite-kysely:/) - assert.match(published[3]!, /^npm:react-native-nitro-sqlite-mikro-orm:/) - assert.match(published[4]!, /^npm:react-native-nitro-sqlite-typeorm:/) + assert.deepEqual( + result.calls + .filter((line) => line.startsWith('npm:')) + .map((line) => line.split(':')[1]), + releasePackages.slice(1), + ) }) test('retry skips TypeORM publication and its publisher check when already published from the selected commit', () => { @@ -108,7 +134,10 @@ test('retry skips TypeORM publication and its publisher check when already publi PUBLISH_TEST_FAIL_OIDC: 'react-native-nitro-sqlite-typeorm', }) assert.equal(result.status, 0, result.stderr) - assert.equal(result.calls.filter((line) => line.startsWith('npm:')).length, 5) + assert.equal( + result.calls.filter((line) => line.startsWith('npm:')).length, + releasePackages.length - 1, + ) assert.equal( result.calls.some((line) => line.startsWith('npm:react-native-nitro-sqlite-typeorm:'), @@ -145,14 +174,7 @@ test('a retry continues when npm still processes a version from the same commit' result.calls .filter((line) => line.startsWith('npm:')) .map((line) => line.split(':')[1]), - [ - 'react-native-nitro-sqlite', - 'react-native-nitro-sqlite-vec', - 'react-native-nitro-sqlite-drizzle', - 'react-native-nitro-sqlite-kysely', - 'react-native-nitro-sqlite-mikro-orm', - 'react-native-nitro-sqlite-typeorm', - ], + releasePackages, ) }) @@ -163,7 +185,10 @@ test('other npm publish failures stop before the next package', () => { assert.equal(result.calls.filter((line) => line.startsWith('npm:')).length, 1) }) -function runPublication(extraEnv: Record = {}) { +function runPublication( + extraEnv: Record = {}, + version = '1.0.0', +) { const directory = mkdtempSync(join(tmpdir(), 'nitro-publish-test-')) const project = join(directory, 'project') const bin = join(directory, 'bin') @@ -172,6 +197,7 @@ function runPublication(extraEnv: Record = {}) { try { mkdirSync(project) mkdirSync(bin) + const integrations = ['vec', 'drizzle', 'kysely', 'mikro-orm', 'typeorm'] for (const [path, name] of [ ['.', 'workspace'], ['examples/react-native', 'react-native-nitro-sqlite-example'], @@ -180,26 +206,32 @@ function runPublication(extraEnv: Record = {}) { 'react-native-nitro-sqlite-example-macos', ], ['packages/react-native-nitro-sqlite', 'react-native-nitro-sqlite'], - ...['vec', 'drizzle', 'kysely', 'mikro-orm', 'typeorm'].map((name) => [ + ...integrations.map((name) => [ `packages/integrations/react-native/${name}`, `react-native-nitro-sqlite-${name}`, ]), + ['packages/nitro-sqlite', 'nitro-sqlite'], + ...integrations.map((name) => [ + `packages/integrations/nitro-ui/${name}`, + `nitro-sqlite-${name}`, + ]), ]) { mkdirSync(join(project, path), { recursive: true }) writeFileSync( join(project, path, 'package.json'), JSON.stringify({ name, - version: '1.0.0', - devDependencies: { 'react-native-nitro-sqlite': '1.0.0' }, - dependencies: { - 'react-native-nitro-sqlite': '1.0.0', - 'react-native-nitro-sqlite-vec': '1.0.0', - 'react-native-nitro-sqlite-drizzle': '1.0.0', - 'react-native-nitro-sqlite-kysely': '1.0.0', - 'react-native-nitro-sqlite-mikro-orm': '1.0.0', - 'react-native-nitro-sqlite-typeorm': '1.0.0', + version, + scripts: name.startsWith('react-native-nitro-sqlite') + ? { lint: 'eslint' } + : {}, + devDependencies: { + 'react-native-nitro-sqlite': version, + 'nitro-sqlite': version, }, + dependencies: Object.fromEntries( + releasePackages.map((dependency) => [dependency, version]), + ), }), ) } @@ -211,7 +243,7 @@ function runPublication(extraEnv: Record = {}) { git('config', 'commit.gpgsign', 'false') git('add', '.') git('commit', '-m', 'chore: create disposable publication fixture') - git('tag', 'v1.0.0') + git('tag', `v${version}`) for (const command of ['bun', 'npm']) { writeFileSync( join(bin, command), @@ -229,7 +261,9 @@ function runPublication(extraEnv: Record = {}) { '" = "bun" ] && [ "$package_name" = "$PUBLISH_TEST_FAIL_BUILD" ] && [ "$*" = "run prepublishOnly" ]; then exit 1; fi', 'if [ "' + command + - '" = "npm" ] && [ "$package_name" = "react-native-nitro-sqlite" ] && [ -n "$PUBLISH_TEST_CORE_STAGED" ]; then echo "npm error 409 Conflict - Cannot publish over previously staged version \\"1.0.0\\"." >&2; exit 1; fi', + '" = "npm" ] && [ "$package_name" = "react-native-nitro-sqlite" ] && [ -n "$PUBLISH_TEST_CORE_STAGED" ]; then echo "npm error 409 Conflict - Cannot publish over previously staged version \\"' + + version + + '\\"." >&2; exit 1; fi', 'if [ "' + command + '" = "npm" ] && [ "$package_name" = "react-native-nitro-sqlite" ] && [ -n "$PUBLISH_TEST_CORE_FAILS" ]; then echo "npm error 403 Forbidden" >&2; exit 1; fi', @@ -244,14 +278,14 @@ function runPublication(extraEnv: Record = {}) { 'globalThis.fetch = async (input) => {', ' const url = String(input)', " if (url.startsWith('https://oidc.example.invalid')) return Response.json({ value: 'fixture-identity' })", - " const name = ['react-native-nitro-sqlite-vec', 'react-native-nitro-sqlite-drizzle', 'react-native-nitro-sqlite-kysely', 'react-native-nitro-sqlite-mikro-orm', 'react-native-nitro-sqlite-typeorm'].find((addon) => url.includes(addon)) ?? 'react-native-nitro-sqlite'", + " const name = decodeURIComponent(url.split('/').at(url.includes('/token/exchange/') ? -1 : -2))", " if (url.includes('/token/exchange/')) {", " appendFileSync(process.env.PUBLISH_TEST_LOG, 'trusted:' + name + '\\n')", " if (name === process.env.PUBLISH_TEST_FAIL_OIDC) return new Response('', { status: 403 })", " return Response.json({ token: 'fixture-exchange' })", ' }', " if (url.endsWith('/latest')) return Response.json({ version: '0.9.0' })", - " if (url.endsWith('/1.0.0')) {", + " if (url.endsWith('/' + process.env.PUBLISH_TEST_VERSION)) {", " const calls = existsSync(process.env.PUBLISH_TEST_LOG) ? readFileSync(process.env.PUBLISH_TEST_LOG, 'utf8') : ''", ' if (name === process.env.PUBLISH_TEST_EXISTING_PACKAGE) return Response.json({ gitHead: process.env.PUBLISH_TEST_EXISTING_COMMIT ?? process.env.PUBLISH_TEST_COMMIT })', " if (calls.includes('npm:' + name + ':')) return Response.json({ gitHead: process.env.PUBLISH_TEST_COMMIT })", @@ -263,7 +297,7 @@ function runPublication(extraEnv: Record = {}) { ) const result = spawnSync( process.execPath, - ['--import', preload, script, '1.0.0'], + ['--import', preload, script, version], { cwd: project, encoding: 'utf8', @@ -272,6 +306,7 @@ function runPublication(extraEnv: Record = {}) { ...extraEnv, PATH: bin + ':' + process.env.PATH, PUBLISH_TEST_LOG: log, + PUBLISH_TEST_VERSION: version, PUBLISH_TEST_COMMIT: git('rev-parse', 'HEAD'), ACTIONS_ID_TOKEN_REQUEST_URL: 'https://oidc.example.invalid/token', ACTIONS_ID_TOKEN_REQUEST_TOKEN: 'fixture-request', diff --git a/scripts/publish-release.ts b/scripts/publish-release.ts index 9b4ab30b..08aa5f81 100644 --- a/scripts/publish-release.ts +++ b/scripts/publish-release.ts @@ -1,4 +1,5 @@ import { execFileSync, spawnSync } from 'node:child_process' +import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { git, validateReleaseVersions } from './release-plan.ts' @@ -26,7 +27,9 @@ export async function publishRelease(version: string): Promise { for (const name of releasePackages) { const cwd = packageDirectory(name) execFileSync('bun', ['run', 'typecheck'], { cwd, stdio: 'inherit' }) - execFileSync('bun', ['run', 'lint'], { cwd, stdio: 'inherit' }) + // The NitroUI packages have no lint setup; their typecheck and prepublish builds still run. + if (hasScript(cwd, 'lint')) + execFileSync('bun', ['run', 'lint'], { cwd, stdio: 'inherit' }) execFileSync('bun', ['run', 'prepublishOnly'], { cwd, stdio: 'inherit' }) } if (git('status', '--porcelain', '--untracked-files=no')) @@ -69,10 +72,20 @@ export async function publishRelease(version: string): Promise { } function packageDirectory(name: string): string { - const prefix = 'react-native-nitro-sqlite-' - return name.startsWith(prefix) - ? `packages/integrations/react-native/${name.slice(prefix.length)}` - : `packages/${name}` + const integration = name.match(/^(react-native-)?nitro-sqlite-(.+)$/) + if (!integration) return `packages/${name}` + const host = integration[1] ? 'react-native' : 'nitro-ui' + return `packages/integrations/${host}/${integration[2]}` +} + +function hasScript(directory: string, script: string): boolean { + const manifest: unknown = JSON.parse( + readFileSync(`${directory}/package.json`, 'utf8'), + ) + if (!manifest || typeof manifest !== 'object' || !('scripts' in manifest)) + return false + const { scripts } = manifest + return !!scripts && typeof scripts === 'object' && script in scripts } if ( diff --git a/scripts/release-plan.ts b/scripts/release-plan.ts index 64a9068c..e33b8cd1 100644 --- a/scripts/release-plan.ts +++ b/scripts/release-plan.ts @@ -109,6 +109,25 @@ export function validateReleaseVersions(version: string): void { 'examples/react-native/macos/package.json', ['dependencies.react-native-nitro-sqlite-typeorm'], ], + ['packages/nitro-sqlite/package.json', ['version']], + ['packages/integrations/nitro-ui/vec/package.json', ['version']], + ['packages/integrations/nitro-ui/drizzle/package.json', ['version']], + [ + 'packages/integrations/nitro-ui/kysely/package.json', + ['version', 'devDependencies.nitro-sqlite'], + ], + [ + 'packages/integrations/nitro-ui/mikro-orm/package.json', + [ + 'version', + 'devDependencies.nitro-sqlite', + 'dependencies.nitro-sqlite-kysely', + ], + ], + [ + 'packages/integrations/nitro-ui/typeorm/package.json', + ['version', 'devDependencies.nitro-sqlite'], + ], ] satisfies [string, string[]][]) { const manifest: unknown = JSON.parse(readFileSync(path, 'utf8')) for (const field of fields) { diff --git a/scripts/release-registry.ts b/scripts/release-registry.ts index 24d6242b..4dc79dab 100644 --- a/scripts/release-registry.ts +++ b/scripts/release-registry.ts @@ -4,7 +4,7 @@ import { prereleaseIdentifiers, } from './release-plan.ts' -/** Packages published together, in dependency order. */ +/** Packages published together, in dependency order: the React Native family, then the NitroUI family. */ export const releasePackages = [ 'react-native-nitro-sqlite', 'react-native-nitro-sqlite-vec', @@ -12,6 +12,12 @@ export const releasePackages = [ 'react-native-nitro-sqlite-kysely', 'react-native-nitro-sqlite-mikro-orm', 'react-native-nitro-sqlite-typeorm', + 'nitro-sqlite', + 'nitro-sqlite-vec', + 'nitro-sqlite-drizzle', + 'nitro-sqlite-kysely', + 'nitro-sqlite-mikro-orm', + 'nitro-sqlite-typeorm', ] /** Select the channel without moving latest backwards on maintenance releases. diff --git a/scripts/release.test.ts b/scripts/release.test.ts index 0738777d..f04f6b0d 100644 --- a/scripts/release.test.ts +++ b/scripts/release.test.ts @@ -87,6 +87,30 @@ test('validates internal dependency versions before publication', () => { }) }) +test('NitroUI package versions and internal pins must match the release version', () => { + for (const [path, field] of [ + ['packages/nitro-sqlite/package.json', 'version'], + ['packages/integrations/nitro-ui/vec/package.json', 'version'], + ['packages/integrations/nitro-ui/kysely/package.json', 'devDependencies'], + ['packages/integrations/nitro-ui/mikro-orm/package.json', 'dependencies'], + ] as const) { + fixture((directory) => { + validateReleaseVersions('1.0.0') + const manifestPath = join(directory, path) + const metadata = JSON.parse(readFileSync(manifestPath, 'utf8')) + if (field === 'version') metadata.version = '0.9.0' + else if (field === 'devDependencies') + metadata.devDependencies['nitro-sqlite'] = '0.9.0' + else metadata.dependencies['nitro-sqlite-kysely'] = '0.9.0' + writeFileSync(manifestPath, JSON.stringify(metadata)) + assert.throws( + () => validateReleaseVersions('1.0.0'), + new RegExp(`${path}: .*does not match`), + ) + }) + } +}) + test('version parsing accepts prereleases and rejects build metadata and unsafe components', () => { assert.deepEqual(parseVersion('10.1.0'), [10, 1, 0]) assert.deepEqual(parseVersion('11.0.0-nitro-v1.0'), [11, 0, 0]) @@ -355,7 +379,7 @@ test('Release Please updates every public version and keeps the configured chang }, ) try { - for (const version of ['2.0.0', '2.0.0-nitro-v1.0']) { + for (const version of ['2.0.0', '2.0.0-nitro-v1.0', '11.0.0-alpha.0']) { const strategy = new Node({ github: client, targetBranch: 'maintenance', @@ -481,6 +505,12 @@ function fixture(run: (directory: string) => void): void { 'packages/integrations/react-native/typeorm/package.json', 'examples/react-native/package.json', 'examples/react-native/macos/package.json', + 'packages/nitro-sqlite/package.json', + 'packages/integrations/nitro-ui/vec/package.json', + 'packages/integrations/nitro-ui/drizzle/package.json', + 'packages/integrations/nitro-ui/kysely/package.json', + 'packages/integrations/nitro-ui/mikro-orm/package.json', + 'packages/integrations/nitro-ui/typeorm/package.json', ]) { mkdirSync(join(directory, path, '..'), { recursive: true }) writeFileSync( @@ -494,8 +524,12 @@ function fixture(run: (directory: string) => void): void { 'react-native-nitro-sqlite-kysely': '1.0.0', 'react-native-nitro-sqlite-mikro-orm': '1.0.0', 'react-native-nitro-sqlite-typeorm': '1.0.0', + 'nitro-sqlite-kysely': '1.0.0', + }, + devDependencies: { + 'react-native-nitro-sqlite': '1.0.0', + 'nitro-sqlite': '1.0.0', }, - devDependencies: { 'react-native-nitro-sqlite': '1.0.0' }, }), ) } diff --git a/shared/orm/materialize.test.mjs b/shared/orm/materialize.test.mjs index 059b252b..f983a0f1 100644 --- a/shared/orm/materialize.test.mjs +++ b/shared/orm/materialize.test.mjs @@ -17,6 +17,7 @@ import { fileURLToPath } from 'node:url' import { materializeOrmSources } from './materialize-sources.mjs' for (const [platform, host] of [ + ['nitro-ui', 'nitro-sqlite'], ['react-native', 'react-native-nitro-sqlite'], ]) { for (const orm of ['kysely', 'mikro-orm']) { diff --git a/tsconfig.json b/tsconfig.json index f385ddff..c3c77b16 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,6 +7,9 @@ { "path": "./packages/integrations/react-native/kysely" }, { "path": "./packages/integrations/react-native/mikro-orm" }, { "path": "./packages/integrations/react-native/typeorm" }, + { "path": "./packages/integrations/nitro-ui/kysely" }, + { "path": "./packages/integrations/nitro-ui/mikro-orm" }, + { "path": "./packages/integrations/nitro-ui/typeorm" }, { "path": "./packages/react-native-nitro-sqlite/plugin/tsconfig.build.json" }, { "path": "./examples/react-native" } ]