@mandujs/core 0.53.1 → 0.53.3

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.
@@ -35,7 +35,7 @@
35
35
  * return {
36
36
  * async findById(id): User | null { ... },
37
37
  * async findMany(limit = 100, offset = 0): User[] { ... },
38
- * async create(row): User { ... }, // PG/SQLite: RETURNING *; MySQL: INSERT + SELECT
38
+ * async create(row): User { ... }, // PG/SQLite: RETURNING *; MySQL: INSERT + re-select
39
39
  * async update(id, patch): User | null { ... },
40
40
  * async delete(id): boolean { ... },
41
41
  * };
@@ -65,7 +65,7 @@ import type { ParsedResource } from "./parser";
65
65
  import type { ResourceField } from "./schema";
66
66
  import { quoteIdent } from "./ddl/emit";
67
67
  import { toSnakeCase } from "./ddl/snapshot";
68
- import { asPersistence, type ExtendedResourcePersistence } from "./ddl/persistence-types";
68
+ import { asPersistence, type ExtendedResourcePersistence, type FieldOverride } from "./ddl/persistence-types";
69
69
  import type { SqlProvider } from "./ddl/types";
70
70
 
71
71
  // ============================================
@@ -172,9 +172,10 @@ function renderRepoFile(
172
172
  const primaryKeyColumn = columns.find((c) => c.primary)?.column ?? "id";
173
173
  const primaryKeyField = columns.find((c) => c.primary)?.field ?? "id";
174
174
  const insertColumns = columns.filter((c) => !c.omitOnInsert);
175
+ const createInputType = createMethodInputType(pascalName, columns);
175
176
 
176
177
  // Quoted identifiers — precomputed so each builder reads cleanly.
177
- const q = (name: string) => quoteIdent(name, provider);
178
+ const q = (name: string) => escapeSqlTemplateText(quoteIdent(name, provider));
178
179
  const qTable = q(table);
179
180
 
180
181
  // Column list for SELECT: we don't use `*` because aliasing
@@ -194,7 +195,7 @@ function renderRepoFile(
194
195
  const body = [
195
196
  findByIdMethod(pascalName, qTable, selectList, q, primaryKeyColumn, primaryKeyField),
196
197
  findManyMethod(pascalName, qTable, selectList),
197
- createMethod(pascalName, table, qTable, selectList, insertColumns, primaryKeyColumn, primaryKeyField, q, provider),
198
+ createMethod(pascalName, table, qTable, selectList, insertColumns, createInputType, primaryKeyColumn, primaryKeyField, q, provider),
198
199
  updateMethod(pascalName, table, qTable, selectList, columns, primaryKeyColumn, primaryKeyField, q, provider),
199
200
  deleteMethod(pascalName, qTable, q, primaryKeyColumn, primaryKeyField, provider),
200
201
  ].join(",\n\n");
@@ -232,7 +233,7 @@ function renderHeader(
232
233
  // - The repo never constructs a Db itself — callers (slots, scripts) pass
233
234
  // in either \`ctx.deps.db\` or a module-level singleton.
234
235
  // - Provider-specific SQL (INSERT ... RETURNING * on PG/SQLite vs
235
- // INSERT + SELECT LAST_INSERT_ID on MySQL) is resolved at generation
236
+ // INSERT + re-select on MySQL) is resolved at generation
236
237
  // time; the generated file has one code path per provider.
237
238
  `;
238
239
  }
@@ -348,6 +349,7 @@ function createMethod(
348
349
  qTable: string,
349
350
  selectList: string,
350
351
  insertColumns: ResolvedColumn[],
352
+ createInputType: string,
351
353
  pkColumn: string,
352
354
  pkField: string,
353
355
  q: (n: string) => string,
@@ -371,7 +373,7 @@ function createMethod(
371
373
  * Insert a new row and return the inserted record. Errors from
372
374
  * constraint violations (UNIQUE, NOT NULL, FK) bubble unchanged.
373
375
  */
374
- async create(input: Omit<${pascalName}, "${pkField}">): Promise<${pascalName}> {
376
+ async create(input: ${createInputType}): Promise<${pascalName}> {
375
377
  const row = await db.one<${pascalName}>\`
376
378
  INSERT INTO ${qTable} (${columnList})
377
379
  VALUES (${valuePlaceholders})
@@ -382,17 +384,20 @@ function createMethod(
382
384
  }`;
383
385
  }
384
386
 
385
- // MySQL: no RETURNING. INSERT then SELECT by LAST_INSERT_ID() OR by the
386
- // primary key if caller provided one. For v1 LCD we use a post-INSERT
387
- // SELECT that matches on the primary-key the caller supplied; if the
388
- // caller omitted it (AUTO_INCREMENT), we fall back to LAST_INSERT_ID().
387
+ const mysqlLookup = insertColumns.some((c) => c.field === pkField)
388
+ ? `${q(pkColumn)} = \${input.${pkField}}`
389
+ : `${q(pkColumn)} = LAST_INSERT_ID()`;
390
+
391
+ // MySQL: no RETURNING. INSERT then SELECT by the supplied primary key when
392
+ // the caller provides it; if the primary key is DB-generated, fall back to
393
+ // LAST_INSERT_ID().
389
394
  return ` /**
390
395
  * Insert a new row and return the inserted record via a follow-up SELECT.
391
396
  * MySQL lacks RETURNING; the generator uses LAST_INSERT_ID() when the
392
397
  * primary key is server-generated, otherwise it re-selects by the
393
398
  * provided primary key value.
394
399
  */
395
- async create(input: Omit<${pascalName}, "${pkField}">): Promise<${pascalName}> {
400
+ async create(input: ${createInputType}): Promise<${pascalName}> {
396
401
  await db\`
397
402
  INSERT INTO ${qTable} (${columnList})
398
403
  VALUES (${valuePlaceholders})
@@ -400,7 +405,7 @@ function createMethod(
400
405
  const row = await db.one<${pascalName}>\`
401
406
  SELECT ${selectList}
402
407
  FROM ${qTable}
403
- WHERE ${q(pkColumn)} = LAST_INSERT_ID()
408
+ WHERE ${mysqlLookup}
404
409
  \`;
405
410
  if (!row) throw new Error("${tableName} create: follow-up SELECT returned no row");
406
411
  return row;
@@ -541,14 +546,7 @@ function resolveColumns(
541
546
  const primary = declaredPkMatch || fieldLevelPk;
542
547
  if (primary) pkCount++;
543
548
 
544
- // Omit PK from INSERT list only when:
545
- // - it's a UUID with a DB-side default (we don't know this at
546
- // generation time for all providers); OR
547
- // - it's an integer and the user didn't explicitly opt in.
548
- // Safe default: let the user supply the PK. The generated
549
- // `Omit<T, pkField>` on `create` means the caller CAN'T pass it
550
- // anyway, so we omit PK from the insert column list unconditionally.
551
- const omitOnInsert = primary;
549
+ const omitOnInsert = primary && hasDbDefault(field, override);
552
550
 
553
551
  columns.push({ field: fieldKey, column, primary, omitOnInsert });
554
552
  }
@@ -575,6 +573,28 @@ function resolveDeclaredPrimaryKey(
575
573
  return declared[0];
576
574
  }
577
575
 
576
+ function createMethodInputType(
577
+ pascalName: string,
578
+ columns: ResolvedColumn[],
579
+ ): string {
580
+ const omittedFields = columns
581
+ .filter((c) => c.omitOnInsert)
582
+ .map((c) => JSON.stringify(c.field));
583
+ if (omittedFields.length === 0) return pascalName;
584
+ return `Omit<${pascalName}, ${omittedFields.join(" | ")}>`;
585
+ }
586
+
587
+ function hasDbDefault(
588
+ field: ResourceField,
589
+ override: FieldOverride | undefined,
590
+ ): boolean {
591
+ return override?.default !== undefined || field.default !== undefined;
592
+ }
593
+
594
+ function escapeSqlTemplateText(text: string): string {
595
+ return text.replace(/`/g, "\\`");
596
+ }
597
+
578
598
  function resolveTableName(
579
599
  resource: ParsedResource,
580
600
  persistence: ExtendedResourcePersistence,
@@ -772,10 +772,11 @@ export function renderToHTML(element: ReactElement, options: SSROptions = {}): s
772
772
  ? generateFastRefreshPreambleTag(isDev, bundleManifest, resolvedCspNonce)
773
773
  : "";
774
774
 
775
- // Issue #191 — DevTools 번들 (~1.15 MB) 주입 결정.
776
- // - 기본: island 하나라도 있을 때만 주입. Pure-SSR 페이지는 0 bytes 다운로드.
777
- // - `devtools === true` → 강제 주입 (SSR-only 프로젝트에서 Kitchen panel 원할 때)
778
- // - `devtools === false` → 강제 스킵 (island 프로젝트에서도 Kitchen 비활성화)
775
+ // Issue #191 + #259 — DevTools 번들 (~1.15 MB) 주입 결정.
776
+ // - 기본 (dev only): 항상 주입. SSR-only 랜딩에서도 Kitchen 패널 사용 가능.
777
+ // - `devtools === true` → 강제 주입 (의미 변화 없음)
778
+ // - `devtools === false` → 강제 스킵 (필요 1.15 MB 절약)
779
+ // 프로덕션 빌드는 `isDev` 가드로 0 bytes 보장.
779
780
  // Cache-bust 은 `manifest.buildTime` 우선, 없으면 `Date.now()`.
780
781
  let devtoolsScript = "";
781
782
  if (isDev && shouldInjectDevtools(devtools, bundleManifest)) {
@@ -1039,27 +1040,27 @@ window.__MANDU_HMR_PORT__ = ${hmrPort};
1039
1040
  }
1040
1041
 
1041
1042
  /**
1042
- * Issue #191 — Determine whether the dev-only `_devtools.js` bundle
1043
- * (~1.15 MB React dev runtime + Kitchen panel) should be injected
1044
- * into the HTML response.
1043
+ * Issue #191 + #259 — Determine whether the dev-only `_devtools.js`
1044
+ * bundle (~1.15 MB React dev runtime + Kitchen panel) should be injected
1045
+ * into the HTML response. The caller gates with `isDev`, so this only
1046
+ * affects dev-mode responses (prod always skips, regardless of the
1047
+ * decision below).
1045
1048
  *
1046
1049
  * Decision table (`devtools` option × manifest shape):
1047
1050
  *
1048
- * | `devtools` | hasIslands | inject? | rationale |
1049
- * |-------------|------------|---------|-----------------------------|
1050
- * | `true` | any | YES | explicit opt-in |
1051
- * | `false` | any | NO | explicit opt-out |
1052
- * | `undefined` | true | YES | default, hydration runtime |
1053
- * | `undefined` | false | NO | pure-SSR save 1.15 MB |
1054
- * | `undefined` | no manifest| NO | nothing to hydrate anyway |
1051
+ * | `devtools` | hasIslands | inject? | rationale |
1052
+ * |-------------|------------|---------|------------------------------|
1053
+ * | `true` | any | YES | explicit opt-in |
1054
+ * | `false` | any | NO | explicit opt-out |
1055
+ * | `undefined` | true | YES | default, hydration runtime |
1056
+ * | `undefined` | false | YES | dev DX: Kitchen on SSR pages |
1057
+ * | `undefined` | no manifest| YES | dev DX: Kitchen pre-build |
1055
1058
  *
1056
- * `hasIslands` is derived from the existing manifest shape rather than
1057
- * a new field, so no bundler-side change is required:
1058
- * - `manifest.islands` is populated only when per-island code
1059
- * splitting produced at least one bundle (build.ts:1654).
1060
- * - `manifest.bundles` entries exist only for routes where
1061
- * `needsHydration()` is true (build.ts:70 filter).
1062
- * Either non-empty ⇒ some route on this server hydrates ⇒ devtools useful.
1059
+ * #259 reverted the original #191 default (skip when no islands): SSR-only
1060
+ * landing/marketing pages are the exact place where Kitchen network/error
1061
+ * panels are most needed, and the 1.15 MB cost only applies in dev — prod
1062
+ * builds never emit `_devtools.js`. Users who explicitly want the old
1063
+ * behavior on a per-app basis can still set `dev.devtools: false`.
1063
1064
  *
1064
1065
  * @internal Exported via `_testOnly_shouldInjectDevtools` below so
1065
1066
  * `tests/runtime/devtools-inject.test.ts` can table-test the matrix
@@ -1067,19 +1068,11 @@ window.__MANDU_HMR_PORT__ = ${hmrPort};
1067
1068
  */
1068
1069
  function shouldInjectDevtools(
1069
1070
  devtools: boolean | undefined,
1070
- manifest: BundleManifest | undefined,
1071
+ _manifest: BundleManifest | undefined,
1071
1072
  ): boolean {
1072
- // Explicit overrides take absolute precedence.
1073
1073
  if (devtools === true) return true;
1074
1074
  if (devtools === false) return false;
1075
-
1076
- // Default behavior: inject only when there is at least one island.
1077
- if (!manifest) return false;
1078
- const hasIslandsMap =
1079
- manifest.islands && Object.keys(manifest.islands).length > 0;
1080
- const hasBundles =
1081
- manifest.bundles && Object.keys(manifest.bundles).length > 0;
1082
- return Boolean(hasIslandsMap || hasBundles);
1075
+ return true;
1083
1076
  }
1084
1077
 
1085
1078
  /**
@@ -80,10 +80,10 @@ export interface StreamingError {
80
80
  export interface StreamingMetrics {
81
81
  /** Shell ready까지 걸린 시간 (ms) */
82
82
  shellReadyTime: number;
83
- /** All ready까지 걸린 시간 (ms) */
84
- allReadyTime: number;
85
- /** Deferred chunk 개수 */
86
- deferredChunkCount: number;
83
+ /** All ready까지 걸린 시간 (ms) */
84
+ allReadyTime: number;
85
+ /** Deferred chunk 개수 */
86
+ deferredChunkCount: number;
87
87
  /** 에러 발생 여부 */
88
88
  hasError: boolean;
89
89
  /** 시작 시간 */
@@ -202,7 +202,7 @@ export interface StreamingSSROptions {
202
202
  }
203
203
 
204
204
  /**
205
- * Issue #191 — Streaming-SSR mirror of `ssr.ts:shouldInjectDevtools`.
205
+ * Issue #191 + #259 — Streaming-SSR mirror of `ssr.ts:shouldInjectDevtools`.
206
206
  * Kept in sync manually (tiny pure function, not worth a cross-module
207
207
  * runtime import — the ssr.ts → streaming-ssr.ts re-export direction
208
208
  * means a circular import here would force a refactor of the whole
@@ -211,16 +211,11 @@ export interface StreamingSSROptions {
211
211
  */
212
212
  function shouldInjectDevtoolsStreaming(
213
213
  devtools: boolean | undefined,
214
- manifest: BundleManifest | undefined,
214
+ _manifest: BundleManifest | undefined,
215
215
  ): boolean {
216
216
  if (devtools === true) return true;
217
217
  if (devtools === false) return false;
218
- if (!manifest) return false;
219
- const hasIslandsMap =
220
- manifest.islands && Object.keys(manifest.islands).length > 0;
221
- const hasBundles =
222
- manifest.bundles && Object.keys(manifest.bundles).length > 0;
223
- return Boolean(hasIslandsMap || hasBundles);
218
+ return true;
224
219
  }
225
220
 
226
221
  /**
@@ -778,10 +773,10 @@ function generateHTMLTailContent(options: StreamingSSROptions): string {
778
773
  scripts.push(generateHMRScript(hmrPort));
779
774
  }
780
775
 
781
- // 11. Issue #191 — DevTools 번들 (~1.15 MB) 주입 결정.
782
- // - 기본: manifest island/bundle 있을 때만 주입 (pure-SSR 페이지는 스킵).
783
- // - `devtools === true` → 강제 주입 (SSR-only 프로젝트에서 Kitchen 원할 ).
784
- // - `devtools === false` 강제 스킵.
776
+ // 11. Issue #191 + #259 — DevTools 번들 (~1.15 MB) 주입 결정.
777
+ // - 기본 (dev only): 항상 주입. SSR-only 랜딩에서도 Kitchen 사용 가능.
778
+ // - `devtools === false` → 강제 스킵 (필요 1.15 MB 절약).
779
+ // - 프로덕션 빌드는 `isDev` 가드로 0 bytes 보장.
785
780
  // - Cache-bust (`?v=buildTime`) 로 HMR 후 stale 방지.
786
781
  if (isDev && shouldInjectDevtoolsStreaming(devtools, bundleManifest)) {
787
782
  scripts.push(generateStreamingDevtoolsScript(bundleManifest));
@@ -1001,9 +996,9 @@ export async function renderToStream(
1001
996
 
1002
997
  // 메트릭 수집
1003
998
  const metrics: StreamingMetrics = {
1004
- shellReadyTime: 0,
1005
- allReadyTime: 0,
1006
- deferredChunkCount: 0,
999
+ shellReadyTime: 0,
1000
+ allReadyTime: 0,
1001
+ deferredChunkCount: 0,
1007
1002
  hasError: false,
1008
1003
  startTime: Date.now(),
1009
1004
  };
@@ -1379,9 +1374,9 @@ export async function renderWithDeferredData(
1379
1374
  const encoder = new TextEncoder();
1380
1375
  const startTime = Date.now();
1381
1376
 
1382
- // 준비된 deferred 스크립트를 담을 배열 (mutable)
1383
- const readyScripts: string[] = [];
1384
- let allDeferredSettled = false;
1377
+ // 준비된 deferred 스크립트를 담을 배열 (mutable)
1378
+ const readyScripts: string[] = [];
1379
+ let allDeferredSettled = false;
1385
1380
 
1386
1381
  // 1. Deferred promises 병렬 시작 (막지 않음!)
1387
1382
  const deferredEntries = Object.entries(deferredPromises);
@@ -1395,11 +1390,11 @@ export async function renderWithDeferredData(
1395
1390
  );
1396
1391
  const data = await Promise.race([promise, timeoutPromise]);
1397
1392
 
1398
- // 스크립트 생성 및 추가
1399
- const script = generateDeferredDataScript(routeId, key, data);
1400
- readyScripts.push(script);
1401
-
1402
- if (isDev) {
1393
+ // 스크립트 생성 및 추가
1394
+ const script = generateDeferredDataScript(routeId, key, data);
1395
+ readyScripts.push(script);
1396
+
1397
+ if (isDev) {
1403
1398
  console.log(`[Mandu Streaming] Deferred ready: ${key} (${Date.now() - startTime}ms)`);
1404
1399
  }
1405
1400
  } catch (error) {
@@ -1473,22 +1468,22 @@ export async function renderWithDeferredData(
1473
1468
 
1474
1469
  // 최종 메트릭 보고 (injectedCount가 실제 메트릭)
1475
1470
  if (onMetrics && baseMetrics) {
1476
- onMetrics({
1477
- ...baseMetrics,
1478
- deferredChunkCount: injectedCount,
1479
- allReadyTime: Date.now() - startTime,
1480
- });
1471
+ onMetrics({
1472
+ ...baseMetrics,
1473
+ deferredChunkCount: injectedCount,
1474
+ allReadyTime: Date.now() - startTime,
1475
+ });
1481
1476
  }
1482
1477
 
1483
1478
  controller.close();
1484
1479
  } catch (error) {
1485
1480
  controller.error(error);
1486
1481
  }
1487
- },
1488
- cancel() {
1489
- void reader.cancel();
1490
- },
1491
- });
1482
+ },
1483
+ cancel() {
1484
+ void reader.cancel();
1485
+ },
1486
+ });
1492
1487
 
1493
1488
  // Phase 7.2 R1 Agent C (H1): if the base stream produced a CSP
1494
1489
  // nonce during shell emission, forward the matching header on the