vite-plugin-postgres-import 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +145 -28
  2. package/package.json +4 -5
  3. package/parse.js +115 -53
  4. package/plugin.js +106 -7
  5. package/index.d.ts +0 -43
package/README.md CHANGED
@@ -37,22 +37,30 @@ delete from t
37
37
  where foo = :foo;
38
38
  ```
39
39
 
40
- `usage.js`:
40
+ `db-runtime.js` (the default runtime, should be mapped to `#db-runtime` via [subpath imports](https://nodejs.org/api/packages.html#subpath-imports)):
41
41
 
42
42
  ```js
43
43
  import { Pool } from "pg";
44
- import { Query, UpdateQuery, QueryMany, MultiStatement } from "./module.sql";
45
44
 
46
- const pool = new Pool("...");
45
+ export const db = new Pool("...");
46
+ ```
47
+
48
+ `usage.js`:
47
49
 
48
- const { id } = await Query(pool, { id: 1 });
50
+ ```js
51
+ import { Query, UpdateQuery, QueryMany, MultiStatement } from "./module.sql";
49
52
 
50
- const rowsUpdated = await UpdateQuery(pool, { id: 1, newFoo: "bar" });
53
+ const { id } = await Query({ id: 1 });
51
54
 
52
- const array = await QueryMany(pool);
55
+ const rowsUpdated = await UpdateQuery({ id: 1, newFoo: "bar" });
56
+
57
+ const array = await QueryMany();
53
58
 
54
59
  // array, object, number respectively
55
- const [all, something, deleted] = await MultiStatement(pool, { foo: "bar" });
60
+ const [all, something, deleted] = await MultiStatement({ foo: "bar" });
61
+
62
+ // override the runtime per call, e.g. to run inside a transaction
63
+ const rowsUpdated = await UpdateQuery({ id: 1, newFoo: "baz" }, { db: tx });
56
64
  ```
57
65
 
58
66
  > [!Warning]
@@ -67,19 +75,19 @@ The only 4 sqlc annotations that are available are the following:
67
75
 
68
76
  - `:execresult` - default if neither of the 3 below are provided, returns `QueryResult`.
69
77
 
70
- ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<QueryResult<R>>`
78
+ ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<QueryResult<R>>`
71
79
 
72
80
  - `:one` - returns template argument, or the default-parsed ones from the select/returning clause.
73
81
 
74
- ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<R>`
82
+ ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<R>`
75
83
 
76
84
  - `:many` - returns template argument as an array, or the default-parsed ones from the select/returning clause.
77
85
 
78
- ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<R[]>`
86
+ ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<R[]>`
79
87
 
80
88
  - `:execrows` - returns number of affected rows.
81
89
 
82
- ex.: `Query(c): Promise<number>`
90
+ ex.: `Query(params?, config?): Promise<number>`
83
91
 
84
92
  4 additional annotations not found in sqlc are available:
85
93
 
@@ -117,25 +125,25 @@ The only 4 sqlc annotations that are available are the following:
117
125
  > import { One as AnotherOne } from "./another-one.sql";
118
126
  >
119
127
  > // definitely don't do this
120
- > await One(c);
121
- > await AnotherOne(c, { id: ... });
128
+ > await One();
129
+ > await AnotherOne({ id: ... });
122
130
  > ```
123
131
  >
124
132
  > At best, you'd get an error in the provided example, due to mismatch in provided values, and at worst, assuming different examples, you'd be getting obscure bugs related to incorrect data.
125
133
 
126
134
  - `:array` - sets `rowMode` to `'array'`. Modifies to type declarations accordingly:
127
135
 
128
- ex. `:execresult`: `Query<R extends any[] = [ ... ]>(c): Promise<QueryArrayResult<R>>`
136
+ ex. `:execresult`: `Query<R extends any[] = [ ... ]>(params?, config?): Promise<QueryArrayResult<R>>`
129
137
 
130
- ex. `:one`: `Query<R extends any[] = [ ... ]>(c): Promise<R>`
138
+ ex. `:one`: `Query<R extends any[] = [ ... ]>(params?, config?): Promise<R>`
131
139
 
132
- ex. `:many`: `Query<R extends any[] = [ ... ]>(c): Promise<R[]>`
140
+ ex. `:many`: `Query<R extends any[] = [ ... ]>(params?, config?): Promise<R[]>`
133
141
 
134
142
  - `:iterable` - returns an `AsyncGenerator`. Once [Async Iterator Helpers](https://github.com/tc39/proposal-async-iterator-helpers)
135
143
  are in the standard, you can use crazy piping as following:
136
144
 
137
145
  ```js
138
- const result = await IterableQuery<{ ... }>(c, { foo: 'bar' })
146
+ const result = await IterableQuery<{ ... }>({ foo: 'bar' })
139
147
  .flatMap(superComplicatedCodeThatIsMoreUsefulToRunFromJS)
140
148
  .filter(Boolean)
141
149
  .toArray();
@@ -146,9 +154,9 @@ some of that computation to JS, you can finally do that! Or at least when that p
146
154
 
147
155
  - `:cursor` - returns an `Cursor`
148
156
 
149
- ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<Cursor<R>>`
157
+ ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<Cursor<R>>`
150
158
 
151
- ex. `:array`: `Query<R extends any[] = [ ... ]>(c): Promise<Cursor<R>>`
159
+ ex. `:array`: `Query<R extends any[] = [ ... ]>(params?, config?): Promise<Cursor<R>>`
152
160
 
153
161
  ## Configuring
154
162
 
@@ -156,7 +164,7 @@ ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<Cursor<R>>`
156
164
 
157
165
  Path to a folder where all declaration are kept relative to `rootFolder`, i.e.
158
166
  a file at path `src/sql/module.sql` will have its `.d.ts` file generated into `${typesFolder}/src/sql/module.sql.d.ts`.
159
- Make sure you include this one in your `tsconfig.json` as `"${typesFolder}/**/*.sql.d.ts"`.
167
+ Make sure you include this one in your tsconfig's `rootDirs` array as `"${typesFolder}/**/*.sql.d.ts"`.
160
168
 
161
169
  _default:_ `'node_modules/@types/vite-plugin-postgres-import/'`
162
170
 
@@ -166,20 +174,129 @@ Root folder relative to which path calculation will be happening. May be useful
166
174
 
167
175
  _default:_ `process.cwd()`
168
176
 
169
- ## What this plugin does NOT do
177
+ ### `runtime`
170
178
 
171
- This plugin does not connect to the database or scan a schema folder, instead naively
172
- parsing select or returning clauses to figure out potential response types.
179
+ Where the default runtime comes from:
180
+
181
+ - `module` - specifier every generated module imports the runtime from. Point it at a module of yours
182
+ (typically via a subpath import) that provides the database connection. _default:_ `'#db-runtime'`
183
+ - `export` - named export of `module` holding the runtime. _default:_ `'db'`
184
+ - `type` - either `'object'` — the export is a `Queryable` (or a promise of one) — or `'function'` — the export
185
+ is called on each query invocation and returns a `Queryable` (or a promise of one). _default:_ `'object'`
186
+
187
+ ## Import aliases
188
+
189
+ If your `package.json` declares [subpath imports](https://nodejs.org/api/packages.html#subpath-imports),
190
+ matching `.sql` files get ambient module declarations generated for their aliased paths:
191
+
192
+ ```json
193
+ {
194
+ "imports": {
195
+ "#sql/*": "./src/sql/*"
196
+ }
197
+ }
198
+ ```
199
+
200
+ With that, `import { Query } from "#sql/module.sql"` is fully typed — declarations land in `${typesFolder}/modules.sql.d.ts`.
201
+ Exact and conditional (`{ "node": ..., "default": ... }`) targets are supported too.
173
202
 
174
- In a real TypeScript project you should probably still roll your own types?
203
+ ## Transactions
175
204
 
176
- And JavaScript projects still get the benefits of completions.
205
+ With the `'function'` runtime type, the runtime is re-evaluated on every query call — which means it can
206
+ consult [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) and pick up
207
+ an _ambient_ transaction: queries anywhere down the call stack automatically run on the transaction's client,
208
+ no threading of `{ db }` through your functions. Combined with
209
+ [explicit resource management](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/await_using)
210
+ you get commit-explicitly, rollback-on-dispose semantics without any callback wrapping.
177
211
 
178
- ## SvelteKit use case
212
+ `vite.config.js`:
179
213
 
180
- I primarily use this in a SvelteKit project. The only thing I modify is setting `typesFolder` to `'.svelte-kit/types'` directory, and adding a `".svelte-kit/types/**/*.sql.d.ts"` record to my `include` array in `tsconfig.json`.
214
+ ```js
215
+ postgres({ runtime: { type: "function" } });
216
+ ```
217
+
218
+ `db-runtime.js`:
219
+
220
+ ```js
221
+ import { AsyncLocalStorage } from "node:async_hooks";
222
+ import { Pool } from "pg";
181
223
 
182
- Also, when using SvelteKit aliases you can absolutely shove all your sql modules in a `src/sql` directory with a `$sql` alias and have module declarations generated for all of the files! Works automagically out of the box.
224
+ const pool = new Pool("...");
225
+ export const als = new AsyncLocalStorage();
226
+
227
+ export const db = () => als.getStore()?.current ?? pool;
228
+
229
+ let spSeq = 0;
230
+
231
+ // pushes a new transaction on the frame,
232
+ // nested calls result in savepoints.
233
+ export async function transaction(begin = "begin") {
234
+ const frame = als.getStore();
235
+
236
+ if (frame.current) {
237
+ // already inside a transaction - nest via a savepoint on the same client
238
+ const client = frame.current;
239
+ const name = `sp_${++spSeq}`;
240
+ await client.query(`savepoint ${name}`);
241
+ let done = false;
242
+ const finish = async (q) => {
243
+ done = true;
244
+ await client.query(q);
245
+ };
246
+ return {
247
+ db: client,
248
+ commit: () => finish(`release savepoint ${name}`),
249
+ rollback: () => finish(`rollback to savepoint ${name}`),
250
+ async [Symbol.asyncDispose]() {
251
+ if (!done) await finish(`rollback to savepoint ${name}`);
252
+ },
253
+ };
254
+ }
255
+
256
+ const client = await pool.connect();
257
+ await client.query(begin);
258
+ frame.current = client;
259
+ let done = false;
260
+ const finish = async (q) => {
261
+ done = true;
262
+ frame.current = undefined;
263
+ try {
264
+ await client.query(q);
265
+ } finally {
266
+ client.release();
267
+ }
268
+ };
269
+ return {
270
+ db: client,
271
+ commit: () => finish("commit"),
272
+ rollback: () => finish("rollback"),
273
+ async [Symbol.asyncDispose]() {
274
+ if (!done) await finish("rollback");
275
+ },
276
+ };
277
+ }
278
+ ```
279
+
280
+ ```js
281
+ import { transaction } from "#db-runtime";
282
+
283
+ await using tx = await transaction();
284
+ await UpdateQuery({ id: 1, newFoo: "bar" });
285
+ await InsertAudit({ id: 1 }); // same transaction, however deep the call stack
286
+ await tx.commit(); // anything thrown before this point rolls back on scope exit
287
+ ```
288
+
289
+ ## Jump to source
290
+
291
+ Generated `.d.ts` files ship with declaration maps pointing back at the original `.sql` file,
292
+ so "Go to Definition" / "Go to Source Definition" on an imported function (or the import path itself) lands you
293
+ on the query source itself. The vite transform also emits a sourcemap, so runtime stack traces
294
+ and debugger stepping map back to the `.sql` source.
295
+
296
+ ## What this plugin does NOT do
297
+
298
+ This plugin does not connect to the database or scan a schema folder, instead naively
299
+ parsing select or returning clauses to figure out potential response types.
183
300
 
184
301
  ## License
185
302
 
package/package.json CHANGED
@@ -1,14 +1,13 @@
1
1
  {
2
2
  "name": "vite-plugin-postgres-import",
3
3
  "description": "Vite plugin for importing SQL files as JS modules with sqlc-style annotations",
4
- "version": "0.7.0",
4
+ "version": "0.8.0",
5
5
  "main": "plugin.js",
6
6
  "type": "module",
7
7
  "author": "SirKostya009",
8
8
  "license": "MIT",
9
9
  "repository": "github:sirkostya009/vite-plugin-postgres-import",
10
10
  "files": [
11
- "index.d.ts",
12
11
  "parse.js"
13
12
  ],
14
13
  "keywords": [
@@ -21,13 +20,13 @@
21
20
  "devDependencies": {
22
21
  "@sveltejs/kit": "^2",
23
22
  "@types/pg": "*",
24
- "vite": "^6"
23
+ "vite": "^8"
25
24
  },
26
25
  "peerDependencies": {
27
26
  "@sveltejs/kit": "^2",
27
+ "@types/pg": "*",
28
28
  "pg": "*",
29
- "pg-cursor": "*",
30
- "@types/pg": "*"
29
+ "pg-cursor": "*"
31
30
  },
32
31
  "peerDependenciesMeta": {
33
32
  "@sveltejs/kit": {
package/parse.js CHANGED
@@ -1,7 +1,5 @@
1
1
  const annotationRegex = /--\s*name:\s*(?<name>[a-zA-Z][\w_]*)\s*(?<tags>(:\w+\s*)*)?\r?\n/g;
2
2
 
3
- const partial = Symbol();
4
-
5
3
  export function* parseModule(/** @type {string} */ sql) {
6
4
  annotationRegex.lastIndex = 0;
7
5
 
@@ -15,13 +13,88 @@ export function* parseModule(/** @type {string} */ sql) {
15
13
  .split(/;\s*$/m)
16
14
  .map((s) => s.trim())
17
15
  .filter(Boolean);
16
+ let queryStart = rema.index + rema[0].length;
17
+ while (queryStart < sql.length && /\s/.test(sql[queryStart])) queryStart++;
18
+ const pos = lineCol(sql, queryStart);
18
19
  if (rest.length > 0) {
19
- const firstMeta = metadata(first);
20
+ const firstMeta = Object.assign(metadata(first), { srcLine: pos.line, srcCol: pos.column });
20
21
  yield [firstMeta, ...rest.map((r) => metadata(r, firstMeta))];
21
22
  } else {
22
- yield metadata(first);
23
+ yield Object.assign(metadata(first), { srcLine: pos.line, srcCol: pos.column });
24
+ }
25
+ }
26
+ }
27
+
28
+ function lineCol(/** @type {string} */ text, /** @type {number} */ index) {
29
+ let line = 0;
30
+ let lineStart = 0;
31
+ for (let i = 0; i < index; ++i) {
32
+ if (text.charCodeAt(i) === 10) {
33
+ line++;
34
+ lineStart = i + 1;
35
+ }
36
+ }
37
+ return { line, column: index - lineStart };
38
+ }
39
+
40
+ const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
41
+
42
+ function vlq(/** @type {number} */ n) {
43
+ let v = n < 0 ? (-n << 1) | 1 : n << 1;
44
+ let out = "";
45
+ do {
46
+ let digit = v & 31;
47
+ v >>>= 5;
48
+ if (v) digit |= 32;
49
+ out += b64[digit];
50
+ } while (v);
51
+ return out;
52
+ }
53
+
54
+ /** @param {{genLine: number, genCol: number, srcIdx?: number, srcLine: number, srcCol: number}[]} mappings */
55
+ export function encodeMappings(mappings) {
56
+ mappings = mappings.toSorted((a, b) => a.genLine - b.genLine || a.genCol - b.genCol);
57
+ let out = "";
58
+ let prevGenLine = 0, prevGenCol = 0, prevSrcIdx = 0, prevSrcLine = 0, prevSrcCol = 0;
59
+ for (const m of mappings) {
60
+ if (m.genLine > prevGenLine) {
61
+ out += ";".repeat(m.genLine - prevGenLine);
62
+ prevGenLine = m.genLine;
63
+ prevGenCol = 0;
64
+ } else if (out) {
65
+ out += ",";
66
+ }
67
+ const srcIdx = m.srcIdx ?? 0;
68
+ out += vlq(m.genCol - prevGenCol) + vlq(srcIdx - prevSrcIdx) + vlq(m.srcLine - prevSrcLine) + vlq(m.srcCol - prevSrcCol);
69
+ prevGenCol = m.genCol;
70
+ prevSrcIdx = srcIdx;
71
+ prevSrcLine = m.srcLine;
72
+ prevSrcCol = m.srcCol;
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /**
78
+ * Locates each module's export declaration in generated text and maps it back to its source position.
79
+ * @param {string} text
80
+ * @param {{name: string, srcLine: number, srcCol: number}[]} moduleMappings
81
+ */
82
+ export function exportMappings(text, moduleMappings, srcIdx = 0, lineOffset = 0) {
83
+ const out = [];
84
+ for (const m of moduleMappings) {
85
+ for (const decl of [`export function ${m.name}`, `export const ${m.name}`, `export async function* ${m.name}`]) {
86
+ let i = text.indexOf(decl);
87
+ while (i >= 0 && /[\w$]/.test(text[i + decl.length] ?? "")) {
88
+ i = text.indexOf(decl, i + 1);
89
+ }
90
+ if (i >= 0) {
91
+ const pos = lineCol(text, i + decl.length - m.name.length);
92
+ out.push({ genLine: pos.line + lineOffset, genCol: pos.column, srcIdx, srcLine: m.srcLine, srcCol: m.srcCol });
93
+ break;
94
+ }
23
95
  }
24
96
  }
97
+ return out;
25
98
  }
26
99
 
27
100
  function metadata(/** @type {string} */ s, /** @type {ReturnType<typeof metadata>} */ firstMeta = undefined) {
@@ -90,13 +163,31 @@ function metadata(/** @type {string} */ s, /** @type {ReturnType<typeof metadata
90
163
  export function codegen(
91
164
  /** @type {Iterable<ReturnType<typeof metadata> | ReturnType<typeof metadata>[]>} */ modules,
92
165
  /** @type {string} */ filename,
93
- /** @type {ReturnType<typeof parseLocalSvelteConfigAliases>} */ aliases
166
+ /** @type {string=} */ moduleName,
167
+ /** @type {{module: string, export: string, type: "object" | "function"}} */ runtime = {
168
+ module: "#db-runtime",
169
+ export: "db",
170
+ type: "object",
171
+ }
94
172
  ) {
95
173
  let dts = [
96
174
  // `declare module '${modulePrefix}${filename}.sql' {`
97
- `import type { QueryResultRow, QueryResult, QueryArrayResult } from 'pg';\nimport { Queryable } from 'vite-plugin-postgres-import';`,
175
+ `import type { QueryResultRow, QueryResult, QueryArrayResult, QueryConfig, QueryArrayConfig, QueryConfigValues, Submittable } from 'pg';
176
+
177
+ interface QueryableObject {
178
+ query<T extends Submittable>(queryStream: T): T;
179
+ query<R extends any[] = any[], I = any[]>(queryConfig: QueryArrayConfig<I>, values?: QueryConfigValues<I>): Promise<QueryArrayResult<R>>;
180
+ query<R extends QueryResultRow = any, I = any>(queryConfig: QueryConfig<I>): Promise<QueryResult<R>>;
181
+ query<R extends QueryResultRow = any, I = any[]>(queryTextOrConfig: string | QueryConfig<I>, values?: QueryConfigValues<I>): Promise<QueryResult<R>>;
182
+ }
183
+
184
+ type Queryable = QueryableObject | Promise<QueryableObject>;`,
185
+ ];
186
+ let js = [
187
+ `import { escapeLiteral } from 'pg';\nimport { ${runtime.export} as __runtime } from '${runtime.module}';`,
98
188
  ];
99
- let js = [`import { escapeLiteral } from 'pg';`];
189
+ const rt = runtime.type === "function" ? "__runtime()" : "__runtime";
190
+ const mappings = [];
100
191
 
101
192
  for (let module of modules) {
102
193
  module = Array.isArray(module)
@@ -119,9 +210,11 @@ export function codegen(
119
210
  module.returnSymbols = module.returnSymbols.map((rs) => [...new Set(rs)]);
120
211
  }
121
212
 
122
- if (module.mode) {
213
+ mappings.push({ name: module.name, srcLine: module.srcLine ?? 0, srcCol: module.srcCol ?? 0 });
214
+
215
+ if (module.mode && !js[0].includes("pg-cursor")) {
123
216
  dts[0] += `\nimport Cursor from 'pg-cursor';`;
124
- js.push(`import Cursor from 'pg-cursor';`);
217
+ js[0] += `\nimport Cursor from 'pg-cursor';`;
125
218
  }
126
219
 
127
220
  const keys = module.params
@@ -148,9 +241,8 @@ export function ${module.name}<${module.returnSymbols
148
241
  }${r.length > 3 ? "\n" : " "}}`
149
242
  )
150
243
  .join(", ")}>(
151
- tx: Queryable,${keys && `\n\tparams: Record<${keys}, unknown>,`}${
152
- module.mode === ":iterable" ? `\n\tread?: number,` : ""
153
- }
244
+ ${keys ? `params: Record<${keys}, unknown>` : `params?: Record<string, never>`},
245
+ config?: { db?: Queryable${module.mode === ":iterable" ? "; read?: number" : ""} },
154
246
  ): ${
155
247
  module.mode === ":cursor"
156
248
  ? `Cursor<R1>`
@@ -194,14 +286,12 @@ export function ${module.name}<${module.returnSymbols
194
286
 
195
287
  js.push(
196
288
  module.mode === ":cursor"
197
- ? `export const ${module.name} = async (tx${
198
- paramsString && `, { ${paramsString} } = {}`
199
- }) => (await tx).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
200
- module.rowArray ? `, { rowMode: "array" }` : ""
201
- }));`
289
+ ? `export const ${module.name} = async ({ ${paramsString} } = {}, { db: __db = ${rt} } = {}) => (await __db).query(new Cursor(\`${
290
+ module.query
291
+ }\`${paramsString && `, [ ${paramsString} ]`}${module.rowArray ? `, { rowMode: "array" }` : ""}));`
202
292
  : module.mode === ":iterable"
203
- ? `export async function* ${module.name}(tx, ${paramsString && `{ ${paramsString} } = {}, `}read = 10) {
204
- const cursor = (await tx).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
293
+ ? `export async function* ${module.name}({ ${paramsString} } = {}, { db: __db = ${rt}, read = 10 } = {}) {
294
+ const cursor = (await __db).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
205
295
  module.rowArray ? `, { rowMode: "array" }` : ""
206
296
  }));
207
297
  try {
@@ -214,10 +304,10 @@ export function ${module.name}<${module.returnSymbols
214
304
  await cursor.close();
215
305
  }
216
306
  }`
217
- : `export const ${module.name} = async (tx, { ${paramsString} } = {}) => (await tx).query({
307
+ : `export const ${module.name} = async ({ ${paramsString} } = {}, { db: __db = ${rt} } = {}) => (await __db).query({
218
308
  ${module.prepared ? `name: "${module.name}",` : ""}
219
- text: \`${module.multiStatement ? module.query : module.query}\`,
220
- values: [ ${module.multiStatement || paramsString} ],
309
+ text: \`${module.query}\`,
310
+ ${module.multiStatement ? "" : `values: [ ${paramsString} ],`}
221
311
  ${module.rowArray ? `rowMode: "array",` : ""}
222
312
  }).then((${module.multiStatement && "["}${module.returnSymbols.map((_, i) => `r${i + 1}`).join()}${
223
313
  module.multiStatement && "]"
@@ -237,38 +327,10 @@ export function ${module.name}<${module.returnSymbols
237
327
  );
238
328
  }
239
329
 
240
- const match = aliases[filename] ?? aliases[partial].find(({ path }) => filename.startsWith(path));
241
330
  let moduleDeclaration = [];
242
- if (match) {
243
- const mod = "path" in match ? match.alias + filename.replace(match.path, "") : match.alias;
244
- moduleDeclaration.push(`declare module "${mod}" {`, dts[0], ...dts.slice(1), `}`);
331
+ if (moduleName) {
332
+ moduleDeclaration.push(`declare module "${moduleName}" {`, dts[0], ...dts.slice(1), `}`);
245
333
  }
246
334
 
247
- return { js: js.join("\n"), dts: dts.join("\n\n") + "\n", moduleDeclaration };
248
- }
249
-
250
- /** @returns {{ [partial]: { path: string; alias: string; }[]; [k: string]: { alias: string } }} */
251
- export async function parseLocalSvelteConfigAliases() {
252
- /** @type {{ default: import('@sveltejs/kit').Config }} */
253
- const { default: svelteConfig } = await import(process.cwd() + "/svelte.config.js").catch(() => ({
254
- default: {},
255
- }));
256
-
257
- const aliases = svelteConfig.kit?.alias ?? {};
258
-
259
- return Object.entries(aliases).reduce(
260
- (acc, [alias, path]) => {
261
- if (path.endsWith(".sql")) {
262
- acc[path] = { alias };
263
- } else {
264
- if (path.endsWith("/*")) {
265
- path = path.substring(0, path.length - 1);
266
- alias = alias.substring(0, alias.length - 1);
267
- }
268
- acc[partial].push({ path, alias });
269
- }
270
- return acc;
271
- },
272
- { [partial]: [] }
273
- );
335
+ return { js: js.join("\n"), dts: dts.join("\n\n") + "\n", moduleDeclaration, mappings };
274
336
  }
package/plugin.js CHANGED
@@ -1,16 +1,62 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { codegen, parseLocalSvelteConfigAliases, parseModule } from "./parse.js";
3
+ import { codegen, encodeMappings, exportMappings, parseModule } from "./parse.js";
4
4
 
5
- /** @returns {import('vite').Plugin} */
5
+ /**
6
+ * @param {object} [opts]
7
+ * @param {string} [opts.typesFolder="node_modules/@types/vite-plugin-postgres-import/"]
8
+ * Path to a folder where all declarations are kept relative to `rootFolder`, i.e. a file at path
9
+ * `src/sql/module.sql` will have its `.d.ts` file generated into `${typesFolder}/src/sql/module.sql.d.ts`.
10
+ * Make sure you include this one in your `tsconfig.json`.
11
+ * @param {string} [opts.rootFolder=process.cwd()]
12
+ * Root folder relative to which path calculation will be happening.
13
+ * @param {object} [opts.runtime] Where the default runtime comes from.
14
+ * @param {string} [opts.runtime.module="#db-runtime"]
15
+ * Module specifier the default runtime is imported from in every generated module.
16
+ * @param {string} [opts.runtime.export="db"]
17
+ * Named export of `runtime.module` providing the default runtime.
18
+ * @param {"object" | "function"} [opts.runtime.type="object"]
19
+ * Whether the runtime export is a `Queryable` itself or a function returning one (possibly async).
20
+ * @returns {Promise<import('vite').Plugin>}
21
+ */
6
22
  export default async function postgres({
7
23
  typesFolder = "node_modules/@types/vite-plugin-postgres-import/",
8
24
  rootFolder = process.cwd(),
25
+ runtime: { module: runtimeModule = "#db-runtime", export: runtimeExport = "db", type: runtimeType = "object" } = {},
9
26
  } = {}) {
10
- const aliases = await parseLocalSvelteConfigAliases();
27
+ const runtime = { module: runtimeModule, export: runtimeExport, type: runtimeType };
28
+ const imports = await fs
29
+ .readFile(path.join(rootFolder, "package.json"), "utf8")
30
+ .then((s) => JSON.parse(s).imports)
31
+ .catch(() => null);
11
32
 
12
33
  const moduleDeclarations = new Map();
13
34
 
35
+ function* targets(/** @type {unknown} */ value) {
36
+ if (typeof value === "string") yield value;
37
+ else if (Array.isArray(value)) for (const v of value) yield* targets(v);
38
+ else if (value) for (const v of Object.values(value)) yield* targets(v);
39
+ }
40
+
41
+ function moduleName(/** @type {string} */ filename) {
42
+ const rel = filename.replaceAll(path.sep, "/");
43
+ for (const [key, value] of Object.entries(imports ?? {})) {
44
+ for (let target of targets(value)) {
45
+ target = target.replace(/^\.\//, "");
46
+ const star = target.indexOf("*");
47
+ if (star < 0) {
48
+ if (target === rel) return key;
49
+ continue;
50
+ }
51
+ const prefix = target.substring(0, star);
52
+ const suffix = target.substring(star + 1);
53
+ if (rel.length >= prefix.length + suffix.length && rel.startsWith(prefix) && rel.endsWith(suffix)) {
54
+ return key.replace("*", rel.substring(prefix.length, rel.length - suffix.length));
55
+ }
56
+ }
57
+ }
58
+ }
59
+
14
60
  return {
15
61
  name: "vite-plugin-sql-postgres",
16
62
  transform: {
@@ -47,18 +93,71 @@ export default async function postgres({
47
93
  }
48
94
  const filename = path.relative(rootFolder, id);
49
95
 
50
- const { js, dts, moduleDeclaration } = codegen(parseModule(sql), filename, aliases);
96
+ const { js, dts, moduleDeclaration, mappings } = codegen(
97
+ parseModule(sql),
98
+ filename,
99
+ moduleName(filename),
100
+ runtime,
101
+ );
51
102
 
52
103
  const dtsFolder = path.join(typesFolder, path.relative(rootFolder, path.dirname(id)));
104
+ const dtsName = path.basename(filename, ".sql") + ".sql.d.ts";
53
105
  await fs.mkdir(dtsFolder, { recursive: true });
54
- await fs.writeFile(path.join(dtsFolder, path.basename(filename, ".sql") + ".sql.d.ts"), dts);
106
+ await fs.writeFile(path.join(dtsFolder, dtsName), dts + `//# sourceMappingURL=${dtsName}.map\n`);
107
+ await fs.writeFile(
108
+ path.join(dtsFolder, dtsName + ".map"),
109
+ JSON.stringify({
110
+ version: 3,
111
+ file: dtsName,
112
+ sources: [path.relative(dtsFolder, id).replaceAll(path.sep, "/")],
113
+ names: [],
114
+ mappings: encodeMappings([
115
+ { genLine: 0, genCol: 0, srcLine: 0, srcCol: 0 },
116
+ ...exportMappings(dts, mappings),
117
+ ]),
118
+ }),
119
+ );
55
120
  if (moduleDeclaration.length) {
56
- moduleDeclarations.set(filename, moduleDeclaration.join("\n"));
57
- await fs.writeFile(path.join(typesFolder, "modules.sql.d.ts"), [...moduleDeclarations.values()].join("\n"));
121
+ moduleDeclarations.set(filename, { text: moduleDeclaration.join("\n"), mappings, id });
122
+ let line = 0;
123
+ const sources = [];
124
+ const combined = [];
125
+ const texts = [];
126
+ for (const { text, mappings, id } of moduleDeclarations.values()) {
127
+ const srcIdx = sources.push(path.relative(typesFolder, id).replaceAll(path.sep, "/")) - 1;
128
+ combined.push({ genLine: line, genCol: 0, srcIdx, srcLine: 0, srcCol: 0 });
129
+ combined.push(...exportMappings(text, mappings, srcIdx, line));
130
+ texts.push(text);
131
+ line += text.split("\n").length;
132
+ }
133
+ await fs.writeFile(
134
+ path.join(typesFolder, "modules.sql.d.ts"),
135
+ texts.join("\n") + "\n//# sourceMappingURL=modules.sql.d.ts.map\n",
136
+ );
137
+ await fs.writeFile(
138
+ path.join(typesFolder, "modules.sql.d.ts.map"),
139
+ JSON.stringify({
140
+ version: 3,
141
+ file: "modules.sql.d.ts",
142
+ sources,
143
+ names: [],
144
+ mappings: encodeMappings(combined),
145
+ }),
146
+ );
58
147
  }
59
148
 
60
149
  return {
61
150
  code: js,
151
+ map: {
152
+ version: 3,
153
+ sources: [id],
154
+ sourcesContent: [sql],
155
+ names: [],
156
+ mappings: encodeMappings([
157
+ { genLine: 0, genCol: 0, srcLine: 0, srcCol: 0 },
158
+ ...exportMappings(js, mappings),
159
+ ]),
160
+ },
62
161
  moduleType: "js",
63
162
  };
64
163
  }
package/index.d.ts DELETED
@@ -1,43 +0,0 @@
1
- import type {
2
- QueryArrayConfig,
3
- QueryArrayResult,
4
- QueryConfig,
5
- QueryConfigValues,
6
- QueryResult,
7
- QueryResultRow,
8
- Submittable,
9
- } from "pg";
10
- import type { Plugin } from "vite";
11
-
12
- export default function postgres(opts?: {
13
- /**
14
- * Path to a folder where all declaration are kept relative to `rootFolder`, i.e. a file at path `src/sql/module.sql` will have its `.d.ts` file generated into `${typesFolder}/src/sql/module.sql.d.ts`. Make sure you include this one in your `tsconfig.json`.
15
- *
16
- * @default "node_modules/@types/vite-plugin-postgres-import/"
17
- */
18
- typesFolder?: string;
19
- /**
20
- * Root folder relative to which path calculation will be happening. May be useful for some I guess.
21
- *
22
- * @default process.cwd()
23
- */
24
- rootFolder?: string;
25
- }): Plugin;
26
-
27
- export interface QueryableObject {
28
- query<T extends Submittable>(queryStream: T): T;
29
-
30
- query<R extends any[] = any[], I = any[]>(
31
- queryConfig: QueryArrayConfig<I>,
32
- values?: QueryConfigValues<I>
33
- ): Promise<QueryArrayResult<R>>;
34
-
35
- query<R extends QueryResultRow = any, I = any>(queryConfig: QueryConfig<I>): Promise<QueryResult<R>>;
36
-
37
- query<R extends QueryResultRow = any, I = any[]>(
38
- queryTextOrConfig: string | QueryConfig<I>,
39
- values?: QueryConfigValues<I>
40
- ): Promise<QueryResult<R>>;
41
- }
42
-
43
- export type Queryable = QueryableObject | Promise<QueryableObject>;