@shing.wong/sure-factor 0.1.1 → 0.2.1

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,136 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are documented here.
4
+ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
+
6
+ ## [0.2.0] - 2026-09-28
7
+
8
+ ### Security
9
+
10
+ - **`sanitizeOutput(value, true)` is no longer a pass-through.** When `richText`
11
+ was true the value was returned verbatim, disabling all sanitisation. The
12
+ function is exported from the package root and had no internal callers, so
13
+ nothing enforced the "already-safe HTML" contract it assumed; any caller
14
+ passing untrusted text was a direct XSS vector.
15
+
16
+ Rich text is now filtered against a tag and attribute allowlist. Disallowed
17
+ elements are dropped while their inner text is kept, raw-text elements
18
+ (`script`, `style`, `textarea`, `title`) are dropped with their body, all
19
+ `on*` handlers are stripped, and `javascript:`, `data:` and `vbscript:` URLs
20
+ are rejected. Safe markup such as `<p>hi <strong>there</strong></p>` is
21
+ unchanged.
22
+
23
+ **Breaking for callers** that passed pre-sanitised HTML containing elements
24
+ outside the allowlist. `table`, `img`, `form`, `input`, `select`, `button`
25
+ and `video` are **not** currently permitted. Review those call sites, or
26
+ sanitize with an allowlist that matches your needs.
27
+
28
+ - **Code injection in generated store files.** `generateStore` interpolated a
29
+ caller-supplied `apiPath` into both single-quoted string literals and template
30
+ literals using one escaper that escaped quotes and backticks but not `$` or
31
+ `{`. An `apiPath` of `/api/${require("fs")}` became live interpolation in the
32
+ generated file, injecting arbitrary code into a consumer's bundle. Escaping is
33
+ now context-specific.
34
+
35
+ ### Fixed
36
+
37
+ - **`parseYaml` silently dropped all but the first item of every object-style
38
+ array.** Six of the fourteen shipped catalog components lost data:
39
+ `crud-resource.yaml` declared 7 columns and kept 2, and `auth-login.yaml`
40
+ parsed to just `email` with `password` dropped. Nothing failed loudly and the
41
+ existing 128 tests all passed. The open array is now tracked with an
42
+ indent-scoped stack, which also handles a block array nested inside an array
43
+ item.
44
+
45
+ - **`introspectSchemaFromDdl` truncated every multi-column table.** The non-greedy
46
+ `([\s\S]*?)\)` stopped at the first `)`, normally inside `VARCHAR(255)` or
47
+ `DEFAULT NOW()`. Replaced with balanced-paren scanning, plus top-level comma
48
+ splitting so `DECIMAL(10, 2)` stays intact.
49
+
50
+ - **`introspectSchemaFromDdl` skipped quoted identifiers.** `CREATE TABLE "User"`
51
+ and names containing spaces (`"user data"`) were not matched. Quoted and
52
+ schema-qualified identifiers are now handled, and a trailing semicolon is
53
+ optional.
54
+
55
+ - **`slice` could wipe a value or emit malformed Unicode.** Non-finite bounds
56
+ turned `'hello'.slice(0, NaN)` into `''`, silently blanking the input.
57
+ Truncating at `maxLength` could also split a surrogate pair. Both are now
58
+ rejected and repaired respectively.
59
+
60
+ - **`normalize` threw `RangeError` on an unknown form.** The form originates in
61
+ free-form catalog or config text, so a typo such as `NFKC1` crashed the
62
+ pipeline. It now falls back to NFKC and warns.
63
+
64
+ - **Anti-spoofing filter had gaps.** The bidi override and embedding set was a
65
+ hand-listed subset that omitted `U+202A`-`U+202C`, the deprecated
66
+ `U+206A`-`U+206F` range, and `U+061C`/`U+200E`/`U+200F`; the C1 control range
67
+ was not stripped at all. An invisible direction-changing character could
68
+ still reorder rendered text.
69
+
70
+ - **Silent failures in `formatCode`.** A broken Prettier install was
71
+ indistinguishable from unparsable input, and the resolved module was cached
72
+ rather than the in-flight promise, so a failed import re-ran on every call.
73
+ The two failure modes are now distinct, the fallback warns, and the import is
74
+ memoized.
75
+
76
+ - **Ignored sanitize steps failed open.** A mistyped step silently disabled that
77
+ transformation with no signal. The documented skip behaviour is unchanged, but
78
+ it now warns.
79
+
80
+ ### Added
81
+
82
+ - **`introspectSchema` is implemented.** It was a stub that always threw
83
+ "Not implemented yet" while silently discarding its `connectionString` and
84
+ `schemas` arguments. It now queries `information_schema` for tables, columns
85
+ and primary/foreign key constraints, honours the `schemas` argument via a bound
86
+ parameter, validates its inputs, and accepts an injected client for testing.
87
+
88
+ - **`pg` is a regular dependency**, so live introspection works without a manual
89
+ install. Previously it would have required `npm install pg`.
90
+
91
+ - **`introspectSchemaFromDdl` and `PostgresConnectionError` are exported from the
92
+ package root.** `introspectSchemaFromDdl` was unreachable from the entry
93
+ point, leaving consumers without a database connection no usable entry point.
94
+
95
+ ### Changed
96
+
97
+ - **Generated string literals now use double quotes.** `esc` switched from
98
+ hand-rolled escaping to `JSON.stringify`, so emitted literals are
99
+ double-quoted where they were previously single-quoted. Semantically
100
+ equivalent; tests asserting the old output were updated.
101
+
102
+ - **Declared `engines.node >= 20`**, matching what ES2022 output and the
103
+ dependency set already required but did not state.
104
+
105
+ - **Test artifacts are no longer emitted into `dist`.** `tsc` previously
106
+ compiled test files into the build output (48 files). A separate
107
+ `tsconfig.build.json` handles this for the emit step only, so `npm run lint`
108
+ still typechecks every test file.
109
+
110
+ - **Unit and end-to-end tests are separated by directory.** `test:e2e` previously
111
+ ran the entire suite with longer timeouts rather than only the browser-backed
112
+ tests, because its vitest config set no `include`. `test:unit` now excludes
113
+ `src/e2e/**` and `test:e2e` includes it; `npm test` runs both.
114
+
115
+ - **Added an `npm run verify` script** covering lint, build, test and package
116
+ export resolution, plus a GitHub Actions workflow that runs it on push and pull
117
+ request.
118
+
119
+ ### Removed
120
+
121
+ - **Removed `src/visual-e2e.test.ts`.** It was tooling for a cross-project
122
+ workflow rather than a test of this package, driving a browser through the
123
+ `agentic-web-testing` MCP server spawned from a hardcoded absolute path to a
124
+ different repository. It could not pass in this checkout and had been failing
125
+ in the default run since the initial commit.
126
+
127
+ ## [0.1.1] - 2026-04-05
128
+
129
+ - Repaired `.gitignore` and completed `.npmignore`.
130
+ - Exposed sync matchers on the root barrel; scoped README imports.
131
+ - Renamed the package to `@shing.wong/sure-factor`.
132
+ - Emit Node-resolvable ESM specifiers.
133
+
134
+ ## [0.1.0]
135
+
136
+ - Initial release.
package/README.md CHANGED
@@ -100,6 +100,10 @@ const schema = introspectSchemaFromDdl(`
100
100
  );
101
101
  `)
102
102
 
103
+ // …or introspect a live database (the `pg` driver ships as a dependency):
104
+ // import { introspectSchema } from '@shing.wong/sure-factor'
105
+ // const live = await introspectSchema(process.env.DATABASE_URL!, ['public'])
106
+
103
107
  // 2. Match — match columns to catalog types
104
108
  const allTypes = loadAllTypesSync()
105
109
  const emailCol = schema.tables[0]!.columns.find(c => c.columnName === 'email')!
@@ -240,6 +244,29 @@ sanitize('<script>alert("xss")</script>', ['htmlEscape'])
240
244
  // → '&lt;script&gt;alert(&quot;xss&quot;)&lt;&#x2F;script&gt;'
241
245
  ```
242
246
 
247
+ ### Rich text output
248
+
249
+ `sanitizeOutput(value, true)` filters rich text through a tag and attribute
250
+ allowlist rather than passing it through:
251
+
252
+ ```ts
253
+ sanitizeOutput('<p>hi <strong>there</strong></p>', true)
254
+ // → '<p>hi <strong>there</strong></p>'
255
+
256
+ sanitizeOutput('<img src=x onerror=alert(1)>', true)
257
+ // → '' (element dropped)
258
+
259
+ sanitizeOutput('<a href="javascript:alert(1)">x</a>', true)
260
+ // → '<a>x</a>' (unsafe URL dropped)
261
+ ```
262
+
263
+ Permitted elements are `a`, `b`, `blockquote`, `br`, `code`, `del`, `em`,
264
+ `h1`-`h6`, `hr`, `i`, `li`, `ol`, `p`, `pre`, `s`, `span`, `strong`, `sub`,
265
+ `sup`, `u` and `ul`, with `class`/`title` on any element and
266
+ `href`/`title`/`rel`/`target` on links. Everything else — including `table`,
267
+ `img`, `form` and every `on*` handler — is dropped. This was a pass-through
268
+ before 0.2.0; see [CHANGELOG.md](./CHANGELOG.md) before upgrading.
269
+
243
270
  ## Serialization
244
271
 
245
272
  Convert between YAML, JSON, XML, and Markdown — useful for exporting catalog definitions:
@@ -310,8 +337,12 @@ git clone git@github.com:ShingWong/sure-factor.git
310
337
  cd sure-factor
311
338
  npm install
312
339
  npm run build
313
- npm test # 132 tests (unit + integration)
314
- npm run test:unit # unit only
315
- npm run test:e2e # Playwright E2E
316
- npm run lint # tsc --noEmit
340
+ npm test # 176 tests (173 unit + 3 Playwright render)
341
+ npm run test:unit # 173, no browser required
342
+ npm run test:e2e # 3, needs `npx playwright install chromium`
343
+ npm run lint # tsc --noEmit, includes test files
344
+ npm run verify # lint + build + test + export check (what CI runs)
317
345
  ```
346
+
347
+ `npm run test:e2e` runs only the tests under `src/e2e/`, which drive a real
348
+ Chromium. `npm run test:unit` covers everything else and needs no browser.
@@ -1 +1 @@
1
- {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AACpD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AAE/D,MAAM,WAAW,eAAgB,SAAQ,eAAe;IACtD,eAAe,EAAE,MAAM,CAAA;IACvB,iBAAiB,EAAE,MAAM,CAAA;IACzB,mBAAmB,EAAE,MAAM,CAAA;IAC3B,qBAAqB,EAAE,MAAM,CAAA;CAC9B;AAED,MAAM,WAAW,oBAAqB,SAAQ,oBAAoB;IAChE,iBAAiB,EAAE,MAAM,CAAA;CAC1B;AAWD,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,GAAE,YAAY,GAAG,MAAM,GAAG,OAAsB,GAAG,OAAO,CAAC,MAAM,CAAC,CActH;AAED,wBAAsB,qBAAqB,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAe7F;AAED,wBAAsB,0BAA0B,CAAC,MAAM,EAAE,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAO5G"}
1
+ {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AACpD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AAE/D,MAAM,WAAW,eAAgB,SAAQ,eAAe;IACtD,eAAe,EAAE,MAAM,CAAA;IACvB,iBAAiB,EAAE,MAAM,CAAA;IACzB,mBAAmB,EAAE,MAAM,CAAA;IAC3B,qBAAqB,EAAE,MAAM,CAAA;CAC9B;AAED,MAAM,WAAW,oBAAqB,SAAQ,oBAAoB;IAChE,iBAAiB,EAAE,MAAM,CAAA;CAC1B;AA2BD,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,GAAE,YAAY,GAAG,MAAM,GAAG,OAAsB,GAAG,OAAO,CAAC,MAAM,CAAC,CA4BtH;AAED,wBAAsB,qBAAqB,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CA2B7F;AAED,wBAAsB,0BAA0B,CAAC,MAAM,EAAE,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAO5G"}
package/dist/format.js CHANGED
@@ -1,13 +1,34 @@
1
- let prettierInstance = null;
1
+ // Memoize the in-flight promise rather than the resolved module. Caching the
2
+ // module only means a rejected import is retried on every call, and concurrent
3
+ // callers each start their own dynamic import.
4
+ let prettierPromise = null;
5
+ class PrettierUnavailableError extends Error {
6
+ constructor(cause) {
7
+ super('Prettier could not be loaded', { cause });
8
+ this.name = 'PrettierUnavailableError';
9
+ }
10
+ }
2
11
  async function getPrettier() {
3
- if (!prettierInstance) {
4
- prettierInstance = await import('prettier');
12
+ if (!prettierPromise) {
13
+ prettierPromise = import('prettier').catch((cause) => {
14
+ // Allow a later call to retry a transient failure, but report the cause.
15
+ prettierPromise = null;
16
+ throw new PrettierUnavailableError(cause);
17
+ });
5
18
  }
6
- return prettierInstance;
19
+ return prettierPromise;
7
20
  }
8
21
  export async function formatCode(code, parser = 'typescript') {
22
+ let prettier;
23
+ try {
24
+ prettier = await getPrettier();
25
+ }
26
+ catch (err) {
27
+ // A broken environment is not the same as unparsable input: every
28
+ // `formatted*` field would be silently unformatted for the whole process.
29
+ throw new PrettierUnavailableError(err);
30
+ }
9
31
  try {
10
- const prettier = await getPrettier();
11
32
  const result = await prettier.format(code, {
12
33
  parser,
13
34
  semi: false,
@@ -17,7 +38,11 @@ export async function formatCode(code, parser = 'typescript') {
17
38
  });
18
39
  return result.trimEnd();
19
40
  }
20
- catch {
41
+ catch (err) {
42
+ // Expected case: the generated snippet is not parseable. Keep the original
43
+ // so generation still succeeds, but make the fallback observable.
44
+ console.warn(`[format] prettier could not parse ${parser} input; emitting unformatted code. ` +
45
+ `Cause: ${err instanceof Error ? err.message : String(err)}`);
21
46
  return code;
22
47
  }
23
48
  }
@@ -28,6 +53,14 @@ export async function formatGeneratedOutput(output) {
28
53
  formatCode(output.validation, 'typescript'),
29
54
  formatCode(output.sanitization, 'typescript'),
30
55
  ]);
56
+ // Surface the risk: identical to the raw field means formatting silently
57
+ // no-op'd, so a caller writing `formatted*` to disk may emit raw code.
58
+ if (formattedRoutes === output.routes &&
59
+ formattedTemplate === output.template &&
60
+ formattedValidation === output.validation &&
61
+ formattedSanitization === output.sanitization) {
62
+ console.warn('[format] every generated field was returned unformatted; check prettier output before writing to disk.');
63
+ }
31
64
  return {
32
65
  ...output,
33
66
  formattedRoutes,
@@ -1 +1 @@
1
- {"version":3,"file":"format.js","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAcA,IAAI,gBAAgB,GAAqC,IAAI,CAAA;AAE7D,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,gBAAgB,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,CAAA;IAC7C,CAAC;IACD,OAAO,gBAAgB,CAAA;AACzB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,IAAY,EAAE,SAA0C,YAAY;IACnG,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,WAAW,EAAE,CAAA;QACpC,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE;YACzC,MAAM;YACN,IAAI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EAAE,UAAU,EAAE,CAAA;IACrB,IAAI,EAAE,cAAc,CAAA;IACpB,IAAI,CAAC,EAAE,aAAa,CAAA;IACpB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,WAAW,oBAAoB;IACnC,aAAa,EAAE,MAAM,CAAA;IACrB,SAAS,EAAE,MAAM,CAAA;IACjB,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,MAAM,CAAA;CACjB;AAwHD,wBAAgB,aAAa,CAAC,OAAO,EAAE,sBAAsB,GAAG,oBAAoB,CAmBnF"}
1
+ {"version":3,"file":"generate-store.d.ts","sourceRoot":"","sources":["../src/generate-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAEjD,MAAM,MAAM,aAAa,GAAG,cAAc,GAAG,cAAc,CAAA;AAC3D,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,WAAW,GAAG,YAAY,CAAA;AAEhE,MAAM,WAAW,sBAAsB;IACrC,SAAS,EAAE,MAAM,CAAA;IACjB,OAAO,EAAE,UAAU,EAAE,CAAA;IACrB,IAAI,EAAE,cAAc,CAAA;IACpB,IAAI,CAAC,EAAE,aAAa,CAAA;IACpB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,WAAW,oBAAoB;IACnC,aAAa,EAAE,MAAM,CAAA;IACrB,SAAS,EAAE,MAAM,CAAA;IACjB,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,MAAM,CAAA;CACjB;AAqJD,wBAAgB,aAAa,CAAC,OAAO,EAAE,sBAAsB,GAAG,oBAAoB,CAqBnF"}
@@ -9,8 +9,32 @@ function toCamelCase(str) {
9
9
  const pascal = toPascalCase(str);
10
10
  return pascal.charAt(0).toLowerCase() + pascal.slice(1);
11
11
  }
12
+ /**
13
+ * Render a value as a single-quoted TypeScript string literal.
14
+ *
15
+ * JSON.stringify is used deliberately: it is a correct JS/TS string escaper, so
16
+ * it neutralises quotes, backslashes and line terminators. It cannot be used
17
+ * inside a template literal, because it leaves `$` and `{` untouched and an
18
+ * interpolated `${...}` would become live code in the generated file — use
19
+ * `templateLiteral` for that case.
20
+ */
12
21
  function esc(val) {
13
- return val.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/`/g, '\\`');
22
+ return JSON.stringify(val);
23
+ }
24
+ /**
25
+ * Render a value for interpolation into a template literal.
26
+ *
27
+ * Escapes backticks, backslashes and `${` so the text cannot terminate the
28
+ * literal or open an interpolation. Newlines are escaped as well to keep the
29
+ * generated source on one line.
30
+ */
31
+ function templateLiteral(val) {
32
+ return val
33
+ .replace(/\\/g, '\\\\')
34
+ .replace(/`/g, '\\`')
35
+ .replace(/\$\{/g, '\\${')
36
+ .replace(/\r/g, '\\r')
37
+ .replace(/\n/g, '\\n');
14
38
  }
15
39
  function tsTypeFromSql(dataType, isNullable) {
16
40
  const base = (() => {
@@ -54,31 +78,36 @@ function generateEntityType(tableName, columns) {
54
78
  }
55
79
  function generateApiAdapter(tableName, apiPath) {
56
80
  const varName = toCamelCase(tableName);
57
- const safePath = esc(apiPath);
81
+ // `apiPath` is interpolated into both single-quoted literals and template
82
+ // literals, so it needs an escaper per context. The old single `esc` covered
83
+ // quotes and backticks but not `${`, letting a crafted path inject live code
84
+ // into the generated file.
85
+ const quotedPath = esc(apiPath);
86
+ const interpolatedPath = templateLiteral(apiPath);
58
87
  return `
59
88
  const ${varName}Api = {
60
89
  list: (): Promise<${toPascalCase(tableName)}[]> =>
61
- fetch('${safePath}').then(r => { if (!r.ok) throw new Error('Failed to fetch'); return r.json() }),
90
+ fetch(${quotedPath}).then(r => { if (!r.ok) throw new Error('Failed to fetch'); return r.json() }),
62
91
 
63
92
  getById: (id: string): Promise<${toPascalCase(tableName)}> =>
64
- fetch(\`${safePath}/\${id}\`).then(r => { if (!r.ok) throw new Error('Not found'); return r.json() }),
93
+ fetch(\`${interpolatedPath}/\${id}\`).then(r => { if (!r.ok) throw new Error('Not found'); return r.json() }),
65
94
 
66
95
  create: (data: Partial<${toPascalCase(tableName)}>): Promise<${toPascalCase(tableName)}> =>
67
- fetch('${safePath}', {
96
+ fetch(${quotedPath}, {
68
97
  method: 'POST',
69
98
  headers: { 'Content-Type': 'application/json' },
70
99
  body: JSON.stringify(data),
71
100
  }).then(r => { if (!r.ok) throw new Error('Failed to create'); return r.json() }),
72
101
 
73
102
  update: (id: string, data: Partial<${toPascalCase(tableName)}>): Promise<${toPascalCase(tableName)}> =>
74
- fetch(\`${safePath}/\${id}\`, {
103
+ fetch(\`${interpolatedPath}/\${id}\`, {
75
104
  method: 'PUT',
76
105
  headers: { 'Content-Type': 'application/json' },
77
106
  body: JSON.stringify(data),
78
107
  }).then(r => { if (!r.ok) throw new Error('Failed to update'); return r.json() }),
79
108
 
80
109
  remove: (id: string): Promise<void> =>
81
- fetch(\`${safePath}/\${id}\`, { method: 'DELETE' }).then(r => { if (!r.ok) throw new Error('Failed to delete'); return }),
110
+ fetch(\`${interpolatedPath}/\${id}\`, { method: 'DELETE' }).then(r => { if (!r.ok) throw new Error('Failed to delete'); return }),
82
111
  }`.trim();
83
112
  }
84
113
  function generateStoreCode(tableName, options) {
@@ -86,10 +115,9 @@ function generateStoreCode(tableName, options) {
86
115
  const varName = toCamelCase(tableName);
87
116
  const sync = options.sync ?? (options.tier === 'production' ? 'server-first' : 'client-first');
88
117
  const versioning = options.versioning ?? (options.tier === 'production');
89
- const safeName = esc(tableName);
90
118
  const configLines = [
91
- ` name: '${safeName}',`,
92
- ` sync: '${sync}',`,
119
+ ` name: ${esc(tableName)},`,
120
+ ` sync: ${esc(sync)},`,
93
121
  ` api: ${varName}Api,`,
94
122
  ];
95
123
  if (versioning) {
@@ -97,7 +125,7 @@ function generateStoreCode(tableName, options) {
97
125
  }
98
126
  if (options.tier !== 'vibe') {
99
127
  configLines.push(` onMutate: (event) => {`);
100
- configLines.push(` console.debug('[${entityName}]', event.kind)`);
128
+ configLines.push(` console.debug(${esc(`[${entityName}]`)}, event.kind)`);
101
129
  configLines.push(` },`);
102
130
  }
103
131
  return `
@@ -109,9 +137,11 @@ ${configLines.map(l => ` ${l}`).join('\n')}
109
137
  }
110
138
  export function generateStore(options) {
111
139
  const { tableName, columns } = options;
112
- const safePath = options.apiPath ? esc(options.apiPath) : `/api/${tableName}`;
140
+ // Pass the raw path through: generateApiAdapter applies the right escaper per
141
+ // literal context. Escaping here as well would double-encode it.
142
+ const rawPath = options.apiPath ?? `/api/${tableName}`;
113
143
  const interfaceCode = generateEntityType(tableName, columns);
114
- const apiCode = generateApiAdapter(tableName, safePath);
144
+ const apiCode = generateApiAdapter(tableName, rawPath);
115
145
  const storeCode = generateStoreCode(tableName, options);
116
146
  const fullCode = [
117
147
  `import { createEntityStore } from 'sure-state'`,
@@ -1 +1 @@
1
- {"version":3,"file":"generate-store.js","sourceRoot":"","sources":["../src/generate-store.ts"],"names":[],"mappings":"AAsBA,SAAS,YAAY,CAAC,GAAW;IAC/B,OAAO,GAAG;SACP,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC;SAC9B,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;SAC9D,IAAI,CAAC,EAAE,CAAC,CAAA;AACb,CAAC;AAED,SAAS,WAAW,CAAC,GAAW;IAC9B,MAAM,MAAM,GAAG,YAAY,CAAC,GAAG,CAAC,CAAA;IAChC,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,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AC,OAAO,IAAI,QAAQ,SAAS,EAAE,CAAA;IACtD,MAAM,aAAa,GAAG,kBAAkB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;IAC5D,MAAM,OAAO,GAAG,kBAAkB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;IACtD,MAAM,SAAS,GAAG,iBAAiB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;IAEvD,MAAM,QAAQ,GAAG;QACf,gDAAgD;QAChD,EAAE;QACF,aAAa;QACb,EAAE;QACF,OAAO;QACP,EAAE;QACF,SAAS;QACT,EAAE;KACH,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAEZ,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAA;AACxD,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { introspectSchema } from './introspect.js';
1
+ export { introspectSchema, introspectSchemaFromDdl, PostgresConnectionError } from './introspect.js';
2
2
  export type { ColumnInfo, TableInfo, SchemaInfo } from './introspect.js';
3
3
  export { matchColumnToType, matchColumnToTypeSync, loadAllTypesSync, type TypeMatchResult } from './match.js';
4
4
  export { generateForTier, type GenerationTier, type GenerateOptions } from './generate.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAClD,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAExE,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAA;AAE7G,OAAO,EAAE,eAAe,EAAE,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,MAAM,eAAe,CAAA;AAC1F,OAAO,EAAE,aAAa,EAAE,KAAK,sBAAsB,EAAE,KAAK,oBAAoB,EAAE,K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,aAAa,CAAA;AAC3F,YAAY,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AACxE,YAAY,EAAE,WAAW,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA"}
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // src/ — Generator engine (introspect → match → generate)
8
8
  //
9
9
  // Public API
10
- export { introspectSchema } from './introspect.js';
10
+ export { introspectSchema, introspectSchemaFromDdl, PostgresConnectionError } from './introspect.js';
11
11
  export { matchColumnToType, matchColumnToTypeSync, loadAllTypesSync } from './match.js';
12
12
  export { generateForTier } from './generate.js';
13
13
  export { generateStore } from './generate-store.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,oEAAoE;AACpE,EAAE;AACF,gBAAgB;AAChB,2EAA2E;AAC3E,0EAA0E;AAC1E,4EAA4E;AAC5E,4EAA4E;AAC5E,EAAE;AACF,aAAa;AACb,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAGlD,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,gBAAgB,EAAwB,MAAM,YAAY,CAAA;AAE7G,OAAO,EAAE,eAAe,EAA6C,MAAM,eAAe,CAAA;AAC1F,OAAO,EAAE,aAAa,EAA8E,MAAM,qBAAqB,CAAA;AAC/H,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AAC9F,OAAO,EAAE,UAAU,EAAE,qBAAqB,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,oEAAoE;AACpE,EAAE;AACF,gBAAgB;AAChB,2EAA2E;AAC3E,0EAA0E;AAC1E,4EAA4E;AAC5E,4EAA4E;AAC5E,EAAE;AACF,aAAa;AACb,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAA;AAGpG,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,gBAAgB,EAAwB,MAAM,YAAY,CAAA;AAE7G,OAAO,EAAE,eAAe,EAA6C,MAAM,eAAe,CAAA;AAC1F,OAAO,EAAE,aAAa,EAA8E,MAAM,qBAAqB,CAAA;AAC/H,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AAC9F,OAAO,EAAE,UAAU,EAAE,qBAAqB,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAA"}
@@ -18,6 +18,30 @@ export interface TableInfo {
18
18
  export interface SchemaInfo {
19
19
  tables: TableInfo[];
20
20
  }
21
- export declare function introspectSchema(connectionString: string, schemas?: string[]): Promise<SchemaInfo>;
21
+ /** Minimal shape of the `pg` query result this module needs. */
22
+ interface QueryResultLike {
23
+ rows: unknown[];
24
+ }
25
+ /**
26
+ * Accepts any object exposing `query`, so both `pg`'s `Client` and a plain test
27
+ * double satisfy it. Row shapes are asserted at the mapping site instead of via
28
+ * a generic, which `pg`'s overloaded `query` signature cannot express cleanly.
29
+ */
30
+ interface Queryable {
31
+ query(sql: string, values?: unknown[]): Promise<QueryResultLike>;
32
+ end?(): Promise<void>;
33
+ }
34
+ export declare class PostgresConnectionError extends Error {
35
+ constructor(cause?: unknown);
36
+ }
37
+ /**
38
+ * Introspect a live PostgreSQL database.
39
+ *
40
+ * Loads the `pg` driver lazily so it stays an optional dependency. `schemas`
41
+ * is honoured rather than ignored: the catalog query is restricted to it, and
42
+ * an empty list is rejected instead of silently introspecting everything.
43
+ */
44
+ export declare function introspectSchema(connectionString: string, schemas?: string[], client?: Queryable): Promise<SchemaInfo>;
22
45
  export declare function introspectSchemaFromDdl(ddl: string): SchemaInfo;
46
+ export {};
23
47
  //# sourceMappingURL=introspect.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"introspect.d.ts","sourceRoot":"","sources":["../src/introspect.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACzB,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,EAAE,OAAO,CAAA;IACnB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;IAC3B,YAAY,EAAE,OAAO,CAAA;IACrB,UAAU,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAA;CACrD;AAED,MAAM,WAAW,SAAS;IACxB,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,UAAU,EAAE,CAAA;CACtB;AAED,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,SAAS,EAAE,CAAA;CACpB;AAED,wBAAsB,gBAAgB,CAAC,gBAAgB,EAAE,MAAM,EAAE,OAAO,GAAE,MAAM,EAAe,GAAG,OAAO,CAAC,UAAU,CAAC,CAEpH;AAED,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CA0C/D"}
1
+ {"version":3,"file":"introspect.d.ts","sourceRoot":"","sources":["../src/introspect.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACzB,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,EAAE,OAAO,CAAA;IACnB,SAAS,EAAE,MAAM,GAAG,IAA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