@objectstack/plugin-pinyin-search 16.1.0 → 17.0.0-rc.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 CHANGED
@@ -1,5 +1,257 @@
1
1
  # @objectstack/plugin-pinyin-search
2
2
 
3
+ ## 17.0.0-rc.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 2e836de: chore(packaging): CHANGELOG.md ships in every npm tarball (#4261)
8
+
9
+ The AGENTS.md post-task checklist requires breaking changesets to carry their
10
+ FROM → TO migration because "this text ships to consumers as `CHANGELOG.md`
11
+ inside the npm package and is what an upgrading agent greps after the tombstone
12
+ error." That delivery path was severed for 68 of the 69 publishable packages:
13
+ npm packs `package.json` / `README*` / `LICENSE*` unconditionally but — unlike
14
+ older npm versions — not `CHANGELOG.md`, and the canonical
15
+ `"files": ["dist", "README.md"]` whitelist never named it. Measured on npm
16
+ 10.9.7: `npm pack --dry-run` on `@objectstack/types` shipped 3 files while its
17
+ 70KB `CHANGELOG.md` stayed behind. Only `@objectstack/spec` listed it
18
+ explicitly.
19
+
20
+ The tombstone-error scenario is precisely the one where the repo is out of
21
+ reach — the upgrading agent has `node_modules` and nothing else — so the
22
+ migration text has to ride in the tarball. Every publishable package now
23
+ declares `CHANGELOG.md` in `files`, and the canonical whitelist is
24
+ `["dist", "README.md", "CHANGELOG.md"]`.
25
+
26
+ The other half is the gate: `check:published-files` gains a fifth invariant,
27
+ COMPLETE — a whitelist that fails to cover `CHANGELOG.md` fails the
28
+ always-required lint job, so the next package cannot silently sever the path
29
+ again. `@objectstack/spec`'s per-package EXTRA_ENTRIES exemption dissolves
30
+ into the canonical set.
31
+
32
+ Consumer-visible change: one more file per install (the package's changelog,
33
+ e.g. 70.8KB for `@objectstack/types`), and `grep -r "removed key"
34
+ node_modules/@objectstack/*/CHANGELOG.md` now finds the migration it was
35
+ promised.
36
+
37
+ - 9881074: fix(batch): the background walks seek instead of counting, so they stop skipping rows (#4363)
38
+
39
+ #4363 made a single paged read a partition of its result set. It could not make
40
+ a _walk_ one: seven background scans paged with a growing `offset` while writing
41
+ to the very rows they were reading, and an offset counts into a set those writes
42
+ are changing. Rows slide past the cursor and are never visited.
43
+
44
+ That is not a slow page in any of these — it is a wrong answer wearing the shape
45
+ of a clean run:
46
+
47
+ - **`rebuildApproverIndex`** built its desired state by walking
48
+ `sys_approval_request WHERE status = 'pending'` with no `orderBy` at all, then
49
+ **deleted** every index row that state did not explain. A skipped request
50
+ meant an approver silently dropped from someone's queue. (The loop beside it
51
+ ordered by `created_at` — not unique, so its pages were never a partition
52
+ either.)
53
+ - **`verifyFileReferences`** decides which files nothing references. A record it
54
+ never visits is reported as an unreferenced file.
55
+ - **`backfillFileReferences`** and the **pinyin companion backfill** rewrite
56
+ each row they read, so their own writes were shifting the set out from under
57
+ the cursor. Records were left unconverted and unsearchable by a run that
58
+ reported success.
59
+ - **`scanValueShapes`** exists to vouch that no stored value is off-shape, and
60
+ it opens a migration gate on that evidence.
61
+
62
+ All of them now go through `keysetWalk` (`@objectstack/types`): order by a
63
+ unique key, and seek past the last one instead of counting from the start. A
64
+ row's key does not move when the row is updated, and cannot be shifted when
65
+ another is deleted, so the walk is stable under exactly the mutation these
66
+ functions perform. It is also O(n) rather than O(n²/page) — measured on
67
+ Postgres over 2M rows, deep pages cost ~1.1 s by offset against ~0.09 s by seek.
68
+
69
+ One deliberate non-conversion: the REST **export** stream keeps its offset. It
70
+ honors a caller-chosen sort, and a keyset walk would have to re-order the export
71
+ by `id` to seek — changing what the user asked for to fix a cost. Its pages are
72
+ already a partition since #4363; only the depth cost remains.
73
+
74
+ `keysetWalk` merges the cursor with `$and` rather than spreading it into the
75
+ caller's filter, so a walk whose own `where` constrains the key column
76
+ (`{ id: { $in: [...] } }`) keeps that constraint instead of having it silently
77
+ overwritten. When a `max` cap is set it reads one row beyond the cap to tell
78
+ "the cap stopped us" from "the source ended exactly there" — without that, a
79
+ walk that read everything still reports `truncated`, and a caller acting on it
80
+ goes looking for rows that were never withheld.
81
+
82
+ The storage suites' fake engines now **throw** on an `offset` instead of serving
83
+ one, so the conversion is pinned rather than merely passing.
84
+
85
+ - cc2de0e: chore(packaging): 20 packages stop publishing their sources, tests and build tooling (#4248)
86
+
87
+ These 20 packages declared no `files` field, so npm fell back to packing the
88
+ whole package directory. `npm pack --dry-run` on `@objectstack/plugin-webhooks`
89
+ listed **21 files** — 15 under `src/`, three of them unit tests
90
+ (`auto-enqueuer.test.ts`, `bootstrap-declared-webhooks.test.ts`, …), plus the
91
+ build-time `scripts/i18n-extract.config.ts`. `dist/` lands on top of that at
92
+ publish time rather than instead of it, so consumers were installing the
93
+ TypeScript sources and the test suite alongside the artifact they asked for.
94
+
95
+ Each now declares `"files": ["dist", "README.md"]`, matching the 29 packages
96
+ that already did. Nothing a consumer imports moves: every `main` / `types` /
97
+ `exports` target in all 20 already resolved inside `dist/`, which the new
98
+ `check:published-files` guard verifies rather than assumes. The visible change
99
+ is a smaller install and a smaller dependency-scanning surface — `npm pack` on
100
+ `@objectstack/plugin-webhooks` now yields 2 files plus `dist/`.
101
+
102
+ The other half of the fix is the gate. Half the packages declaring `files` and
103
+ half not was the #3786 shape — a hand-copied convention with nothing enforcing
104
+ it, where whoever forgets the line gets no signal at all. `check:published-files`
105
+ (new, wired into the always-required `lint` job) holds every non-private
106
+ workspace package to four invariants: `files` is **declared**; it is
107
+ **sufficient** (covers every entry point, so tightening a whitelist cannot ship
108
+ a package that fails to resolve); it is **minimal** (admits no test, test-harness
109
+ config or build script); and anything beyond `dist` + `README.md` is
110
+ **registered** with a reason, reconciled in both directions so a stale exemption
111
+ is an error rather than dead text. `@objectstack/spec` is the one package with
112
+ registered extras — its `.zod.ts` sources, JSON Schemas, liveness ledgers and
113
+ `CHANGELOG.md` are product, not build input.
114
+
115
+ This also closes an assumption #4206 was resting on. Excluding `<pkg>/scripts/**`
116
+ from the docs-drift implementation test is sound only while no package publishes
117
+ `scripts/` as runtime code; that held, but it held because someone read all three
118
+ offenders by hand. It is now checked on every PR.
119
+
120
+ - Updated dependencies [48fcf70]
121
+ - Updated dependencies [3ec8186]
122
+ - Updated dependencies [b1863a5]
123
+ - Updated dependencies [270650f]
124
+ - Updated dependencies [956e7f9]
125
+ - Updated dependencies [3aef718]
126
+ - Updated dependencies [ffb003c]
127
+ - Updated dependencies [32ccb23]
128
+ - Updated dependencies [2d3e255]
129
+ - Updated dependencies [7d7521f]
130
+ - Updated dependencies [8d895ff]
131
+ - Updated dependencies [2af1988]
132
+ - Updated dependencies [0af50a3]
133
+ - Updated dependencies [2e836de]
134
+ - Updated dependencies [c20b875]
135
+ - Updated dependencies [2a37694]
136
+ - Updated dependencies [3c628ce]
137
+ - Updated dependencies [ed77493]
138
+ - Updated dependencies [58a03d2]
139
+ - Updated dependencies [c39d713]
140
+ - Updated dependencies [91f4c78]
141
+ - Updated dependencies [45dc446]
142
+ - Updated dependencies [ab9fb5c]
143
+ - Updated dependencies [f985b3f]
144
+ - Updated dependencies [9881074]
145
+ - Updated dependencies [7777e8f]
146
+ - Updated dependencies [507b92a]
147
+ - Updated dependencies [39eb01b]
148
+ - Updated dependencies [55bbefc]
149
+ - Updated dependencies [7ce02eb]
150
+ - Updated dependencies [d13004a]
151
+ - Updated dependencies [be7360c]
152
+ - Updated dependencies [8675db6]
153
+ - Updated dependencies [b09d8d9]
154
+ - Updated dependencies [af2a095]
155
+ - Updated dependencies [bf478e1]
156
+ - Updated dependencies [77fadbf]
157
+ - Updated dependencies [5c13368]
158
+ - Updated dependencies [857a6cf]
159
+ - Updated dependencies [d5749d7]
160
+ - Updated dependencies [d92c72d]
161
+ - Updated dependencies [5d21a48]
162
+ - Updated dependencies [e4c2dc8]
163
+ - @objectstack/objectql@17.0.0-rc.1
164
+ - @objectstack/core@17.0.0-rc.1
165
+ - @objectstack/types@17.0.0-rc.1
166
+
167
+ ## 17.0.0-rc.0
168
+
169
+ ### Patch Changes
170
+
171
+ - 9f060e5: chore(deps)!: better-auth 1.7.0-rc.2 (account identity restructuring) + the
172
+ production-dependency batch from #3517
173
+
174
+ **better-auth 1.7.0-rc.1 → 1.7.0-rc.2** across the family (`better-auth`,
175
+ `@better-auth/core`, `@better-auth/oauth-provider`, `@better-auth/sso`, and the
176
+ adapter/telemetry overrides). `@better-auth/scim` deliberately stays on
177
+ 1.7.0-rc.1 — rc.2 replaces its whole model (code-defined connections; the
178
+ `scimProvider` model and the generate-token endpoint are gone), which is a
179
+ feature migration, not a version bump. Its peer range accepts rc.2 core, and the
180
+ advisory that forced the original pin (GHSA-j8v8-g9cx-5qf4) is still fixed.
181
+
182
+ **BREAKING — account identity.** better-auth renamed `account.accountId` to
183
+ `account.providerAccountId` and added a REQUIRED `account.issuer`; sign-in now
184
+ resolves accounts by `(issuer, providerAccountId)`.
185
+
186
+ - FROM `fields: { accountId: 'account_id' }` → TO
187
+ `fields: { issuer: 'issuer', providerAccountId: 'account_id' }`. The provider
188
+ account id keeps its `account_id` column — only the better-auth-side name
189
+ moved — and `sys_account` gains an `issuer` column.
190
+ - FROM `internalAdapter.createAccount({ providerId, accountId, … })` → TO
191
+ `createAccount({ providerId, issuer, providerAccountId, … })`. A local
192
+ password account carries the issuer better-auth mints for itself,
193
+ `local:credential`.
194
+ - FROM `client.auth.accounts.unlink({ providerId, accountId })` → TO
195
+ `unlink({ accountId })`, where `accountId` is now the account ROW id (the `id`
196
+ from `accounts.list()`), matching better-auth's narrowed body.
197
+ `accounts.list()` returns `issuer` + `providerAccountId` in place of
198
+ `accountId`.
199
+
200
+ **Existing deployments:** rows written before 1.7 have no issuer and are
201
+ invisible to sign-in until stamped. The auth plugin now runs an idempotent
202
+ boot-time backfill that stamps what it can derive — `local:credential` for
203
+ password accounts, `local:oauth:<providerId>` for configured social providers,
204
+ and the registered IdP's real `iss` from `sys_sso_provider` for federated ones.
205
+ Accounts from a federated IdP that is no longer registered cannot be derived;
206
+ they are logged with their provider id and row count rather than guessed, and
207
+ those users cannot sign in through that provider until the row is stamped with
208
+ the IdP's issuer or removed so a fresh login re-links it.
209
+
210
+ **Also required by 1.7:** `SecondaryStorage` gained two mandatory methods, both
211
+ now implemented over the kernel cache service — `getAndDelete` (single-use
212
+ verification values) and `increment` (fixed-window rate-limit counter;
213
+ `rateLimit.storage: 'secondary-storage'` throws at boot without it).
214
+
215
+ The rest of #3517's production-dependency batch rides along: `@oclif/core`
216
+ 4.13.0, `@hono/node-server` 2.0.12, `hono` 4.12.32, `tar` 7.5.22, `jose` 6.2.4,
217
+ `pinyin-pro` 3.28.2, plus the private docs app's fumadocs/next/react bumps.
218
+
219
+ - Updated dependencies [6169615]
220
+ - Updated dependencies [fa3d0cf]
221
+ - Updated dependencies [a749273]
222
+ - Updated dependencies [fdb4f50]
223
+ - Updated dependencies [879ea13]
224
+ - Updated dependencies [840ee4b]
225
+ - Updated dependencies [ad4af62]
226
+ - Updated dependencies [d44dbfa]
227
+ - Updated dependencies [b949059]
228
+ - Updated dependencies [c5ff96d]
229
+ - Updated dependencies [48c110e]
230
+ - Updated dependencies [87aca93]
231
+ - Updated dependencies [32d3800]
232
+ - Updated dependencies [a227ed7]
233
+ - Updated dependencies [763931e]
234
+ - Updated dependencies [de9af8a]
235
+ - Updated dependencies [5d4de37]
236
+ - Updated dependencies [0e3a226]
237
+ - Updated dependencies [4cca74c]
238
+ - Updated dependencies [81ce41a]
239
+ - Updated dependencies [85e1e4e]
240
+ - Updated dependencies [e1fa8d5]
241
+ - Updated dependencies [402f534]
242
+ - Updated dependencies [030125b]
243
+ - Updated dependencies [8e08bc3]
244
+ - Updated dependencies [0c302a7]
245
+ - Updated dependencies [5f0852f]
246
+ - Updated dependencies [cde1975]
247
+ - Updated dependencies [20cb232]
248
+ - Updated dependencies [e231abb]
249
+ - Updated dependencies [b95577a]
250
+ - Updated dependencies [54f479a]
251
+ - @objectstack/objectql@17.0.0-rc.0
252
+ - @objectstack/core@17.0.0-rc.0
253
+ - @objectstack/types@17.0.0-rc.0
254
+
3
255
  ## 16.1.0
4
256
 
5
257
  ### Patch Changes
package/dist/index.js CHANGED
@@ -40,10 +40,11 @@ __export(index_exports, {
40
40
  module.exports = __toCommonJS(index_exports);
41
41
 
42
42
  // src/pinyin-search-plugin.ts
43
- var import_types = require("@objectstack/types");
43
+ var import_types2 = require("@objectstack/types");
44
44
 
45
45
  // src/companion-projection.ts
46
46
  var import_objectql2 = require("@objectstack/objectql");
47
+ var import_types = require("@objectstack/types");
47
48
 
48
49
  // src/pinyin.ts
49
50
  var import_objectql = require("@objectstack/objectql");
@@ -114,47 +115,44 @@ async function backfillSearchCompanion(engine, logger, options) {
114
115
  const sources = (0, import_objectql2.resolveSearchCompanionSources)(schema);
115
116
  if (sources.length === 0) continue;
116
117
  result.objects++;
117
- let offset = 0;
118
- for (; ; ) {
119
- let rows = [];
120
- try {
121
- rows = await engine.find(schema.name, {
122
- fields: ["id", ...sources, import_objectql2.SEARCH_COMPANION_FIELD],
123
- limit: batchSize,
124
- offset,
125
- context: SYSTEM_CTX
126
- });
127
- } catch (err) {
128
- logger?.warn?.("[pinyin-search] backfill scan failed", { object: schema.name, error: err?.message });
129
- break;
130
- }
131
- if (!rows?.length) break;
132
- result.scanned += rows.length;
133
- for (const row of rows) {
134
- if (row?.id == null) continue;
135
- const hasBlob = typeof row[import_objectql2.SEARCH_COMPANION_FIELD] === "string" && row[import_objectql2.SEARCH_COMPANION_FIELD] !== "";
136
- const hasCjkSource = sources.some((s) => (0, import_objectql2.containsCJK)(row[s]));
137
- if (!options?.force && (hasBlob || !hasCjkSource)) continue;
138
- try {
139
- const value = await computeSearchCompanionValue(sources.map((s) => row[s]));
140
- if (!options?.force && value == null) continue;
141
- if (value === row[import_objectql2.SEARCH_COMPANION_FIELD]) continue;
142
- await engine.update(
143
- schema.name,
144
- { id: row.id, [import_objectql2.SEARCH_COMPANION_FIELD]: value },
145
- { context: SYSTEM_CTX }
146
- );
147
- result.updated++;
148
- } catch (err) {
149
- logger?.warn?.("[pinyin-search] backfill row skipped", {
150
- object: schema.name,
151
- id: row.id,
152
- error: err?.message
153
- });
118
+ const walk = (0, import_types.keysetWalk)(
119
+ (q) => engine.find(schema.name, {
120
+ ...q,
121
+ fields: ["id", ...sources, import_objectql2.SEARCH_COMPANION_FIELD],
122
+ context: SYSTEM_CTX
123
+ }),
124
+ { pageSize: batchSize }
125
+ );
126
+ try {
127
+ for await (const rows of walk.pages()) {
128
+ result.scanned += rows.length;
129
+ for (const row of rows) {
130
+ if (row?.id == null) continue;
131
+ const hasBlob = typeof row[import_objectql2.SEARCH_COMPANION_FIELD] === "string" && row[import_objectql2.SEARCH_COMPANION_FIELD] !== "";
132
+ const hasCjkSource = sources.some((s) => (0, import_objectql2.containsCJK)(row[s]));
133
+ if (!options?.force && (hasBlob || !hasCjkSource)) continue;
134
+ try {
135
+ const value = await computeSearchCompanionValue(sources.map((s) => row[s]));
136
+ if (!options?.force && value == null) continue;
137
+ if (value === row[import_objectql2.SEARCH_COMPANION_FIELD]) continue;
138
+ await engine.update(
139
+ schema.name,
140
+ { id: row.id, [import_objectql2.SEARCH_COMPANION_FIELD]: value },
141
+ { context: SYSTEM_CTX }
142
+ );
143
+ result.updated++;
144
+ } catch (err) {
145
+ logger?.warn?.("[pinyin-search] backfill row skipped", {
146
+ object: schema.name,
147
+ id: row.id,
148
+ error: err?.message
149
+ });
150
+ }
154
151
  }
155
152
  }
156
- if (rows.length < batchSize) break;
157
- offset += batchSize;
153
+ } catch (err) {
154
+ logger?.warn?.("[pinyin-search] backfill scan failed", { object: schema.name, error: err?.message });
155
+ continue;
158
156
  }
159
157
  }
160
158
  if (result.updated > 0) {
@@ -176,7 +174,7 @@ var PinyinSearchPlugin = class {
176
174
  this.options = options;
177
175
  }
178
176
  get enabled() {
179
- return this.options.enabled ?? (0, import_types.resolveSearchPinyinEnabled)();
177
+ return this.options.enabled ?? (0, import_types2.resolveSearchPinyinEnabled)();
180
178
  }
181
179
  async init(_ctx) {
182
180
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/pinyin-search-plugin.ts","../src/companion-projection.ts","../src/pinyin.ts"],"sourcesContent":["// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport { PinyinSearchPlugin } from './pinyin-search-plugin.js';\nexport type { PinyinSearchPluginOptions } from './pinyin-search-plugin.js';\nexport {\n bindSearchCompanionHooks,\n backfillSearchCompanion,\n rebuildSearchCompanion,\n PINYIN_SEARCH_HOOK_PACKAGE,\n} from './companion-projection.js';\nexport type {\n CompanionBackfillOptions,\n CompanionBackfillResult,\n} from './companion-projection.js';\nexport { computeSearchCompanionValue } from './pinyin.js';\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * PinyinSearchPlugin (#2486) — pinyin recall for `$search`.\n *\n * Pure hook plugin: the `__search` companion column is declared at object\n * compile time by the SchemaRegistry (gated on the SAME\n * `OS_SEARCH_PINYIN_ENABLED` decision point), the engine ORs it into the\n * `$search` filter, and this plugin fills the value:\n *\n * - before-save hooks: recompute full pinyin + initials of the\n * display/name field when it changes;\n * - boot backfill (`kernel:bootstrapped`): fill rows that predate the\n * switch or arrived via hook-bypassing writes;\n * - `rebuildSearchCompanion` (exported): explicit reconcile/rebuild entry.\n *\n * When the flag is off the plugin is inert: no hooks, no backfill, and\n * `pinyin-pro` is never imported.\n */\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport { resolveSearchPinyinEnabled } from '@objectstack/types';\nimport {\n bindSearchCompanionHooks,\n backfillSearchCompanion,\n} from './companion-projection.js';\n\nexport interface PinyinSearchPluginOptions {\n /**\n * Force-enable/disable regardless of `OS_SEARCH_PINYIN_ENABLED` (tests /\n * embedders). Default: `resolveSearchPinyinEnabled()`.\n */\n enabled?: boolean;\n /** Skip the boot backfill (default: run it once per boot). */\n backfill?: boolean;\n}\n\nexport class PinyinSearchPlugin implements Plugin {\n name = 'com.objectstack.plugin.pinyin-search';\n version = '1.0.0';\n type = 'standard';\n dependencies = ['com.objectstack.engine.objectql'];\n\n private readonly options: PinyinSearchPluginOptions;\n\n constructor(options: PinyinSearchPluginOptions = {}) {\n this.options = options;\n }\n\n private get enabled(): boolean {\n return this.options.enabled ?? resolveSearchPinyinEnabled();\n }\n\n async init(_ctx: PluginContext): Promise<void> {\n // Nothing to register: the companion column is provisioned by the\n // SchemaRegistry's compile-time seam, not injected at runtime.\n }\n\n async start(ctx: PluginContext): Promise<void> {\n if (!this.enabled) {\n ctx.logger.debug?.('PinyinSearchPlugin: OS_SEARCH_PINYIN_ENABLED is off — inert');\n return;\n }\n\n ctx.hook('kernel:ready', async () => {\n const engine = this.resolveEngine(ctx);\n if (!engine) {\n ctx.logger.warn('PinyinSearchPlugin: no ObjectQL engine — companion hooks NOT bound');\n return;\n }\n try {\n bindSearchCompanionHooks(engine, ctx.logger as any);\n } catch (err: any) {\n ctx.logger.warn('PinyinSearchPlugin: companion hooks not bound', { error: err?.message });\n }\n });\n\n // Backfill AFTER boot settles (`kernel:bootstrapped` fires once every\n // `kernel:ready` hook — including seed loading — has completed), so\n // seeded rows written before/around hook binding are reconciled too.\n if (this.options.backfill !== false) {\n ctx.hook('kernel:bootstrapped', async () => {\n const engine = this.resolveEngine(ctx);\n if (!engine) return;\n try {\n await backfillSearchCompanion(engine, ctx.logger as any);\n } catch (err: any) {\n ctx.logger.warn('PinyinSearchPlugin: companion backfill failed', { error: err?.message });\n }\n });\n }\n }\n\n private resolveEngine(ctx: PluginContext): any {\n try {\n return ctx.getService<any>('objectql');\n } catch {\n try {\n return ctx.getService<any>('data');\n } catch {\n return null;\n }\n }\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * `__search` companion-column projection (#2486).\n *\n * The column itself is DECLARED at object compile time by the SchemaRegistry\n * (`provisionSearchCompanion`, gated on `OS_SEARCH_PINYIN_ENABLED`); this\n * module only FILLS the value — the `plugin-sharing` primary-BU projection\n * pattern (column on the object, plugin maintains it via hooks).\n *\n * Write path: global `beforeInsert`/`beforeUpdate` hooks stamp\n * `data.__search` whenever a companion source field (the object's\n * display/name field) is present in the write — i.e. only when the source\n * actually changed, avoiding write amplification. Writes that bypass hooks\n * (bulk import, direct migration) leave the companion empty; the boot\n * backfill and the `rebuildSearchCompanion` reconcile entry cover that.\n */\n\nimport {\n SEARCH_COMPANION_FIELD,\n resolveSearchCompanionSources,\n containsCJK,\n} from '@objectstack/objectql';\nimport { computeSearchCompanionValue } from './pinyin.js';\n\nconst SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const;\n\nexport const PINYIN_SEARCH_HOOK_PACKAGE = 'plugin-pinyin-search:companion';\n\ninterface MinimalEngine {\n registerHook(\n event: string,\n handler: (ctx: any) => any | Promise<any>,\n options?: { object?: string | string[]; priority?: number; packageId?: string },\n ): void;\n unregisterHooksByPackage(packageId: string): number;\n find(object: string, query?: any, options?: any): Promise<any[]>;\n update(object: string, data: any, options?: any): Promise<any>;\n registry?: {\n getObject(name: string): any;\n getAllObjects?(packageId?: string): any[];\n };\n}\n\ninterface MinimalLogger {\n info?: (msg: any, ...rest: any[]) => void;\n warn?: (msg: any, ...rest: any[]) => void;\n debug?: (msg: any, ...rest: any[]) => void;\n}\n\n/**\n * Stamp `data.__search` on a before-save hook context when a companion source\n * field is part of the write. Recomputes from the NEW value; a non-CJK new\n * value clears the companion (null) so stale pinyin never recalls a renamed\n * record. Never throws — a normalization failure must not fail the write.\n */\nasync function stampCompanion(engine: MinimalEngine, ctx: any, logger?: MinimalLogger): Promise<void> {\n const object = ctx?.object;\n if (!object) return;\n const schema = engine.registry?.getObject?.(object);\n if (!schema?.fields?.[SEARCH_COMPANION_FIELD]) return;\n\n const data = ctx?.input?.data;\n if (!data || typeof data !== 'object' || Array.isArray(data)) return;\n\n const sources = resolveSearchCompanionSources(schema);\n if (sources.length === 0) return;\n const touched = sources.filter((s) => Object.prototype.hasOwnProperty.call(data, s));\n if (touched.length === 0) return; // source unchanged → no recompute (no write amplification)\n\n try {\n data[SEARCH_COMPANION_FIELD] = await computeSearchCompanionValue(sources.map((s) => data[s]));\n } catch (err: any) {\n logger?.warn?.('[pinyin-search] companion normalization failed — write proceeds without it', {\n object,\n error: err?.message,\n });\n }\n}\n\n/**\n * Bind the global before-save hooks that keep `__search` in step. Idempotent\n * (unbinds the package first). Hooks are global (no object filter) with a\n * cheap early-out: objects without a provisioned companion column return\n * immediately. They run for system-context writes too — the projection must\n * stay correct regardless of who writes (seeds, imports, admin UI).\n */\nexport function bindSearchCompanionHooks(engine: MinimalEngine, logger?: MinimalLogger): void {\n if (typeof engine.registerHook !== 'function') return;\n if (typeof engine.unregisterHooksByPackage === 'function') {\n engine.unregisterHooksByPackage(PINYIN_SEARCH_HOOK_PACKAGE);\n }\n const opts = { packageId: PINYIN_SEARCH_HOOK_PACKAGE, priority: 150 };\n const handler = (ctx: any) => stampCompanion(engine, ctx, logger);\n engine.registerHook('beforeInsert', handler, opts);\n engine.registerHook('beforeUpdate', handler, opts);\n logger?.info?.('[pinyin-search] companion hooks bound (beforeInsert/beforeUpdate, all objects)');\n}\n\nexport interface CompanionBackfillOptions {\n /** Rows fetched per page during the scan. Default 1000. */\n batchSize?: number;\n /** Restrict to one object (reconcile entry); default: every provisioned object. */\n object?: string;\n /**\n * Recompute EVERY row's companion, not just missing ones — the periodic\n * reconcile/rebuild mode. Default false (backfill: only rows whose\n * companion is empty but whose source has CJK content).\n */\n force?: boolean;\n}\n\nexport interface CompanionBackfillResult {\n objects: number;\n scanned: number;\n updated: number;\n}\n\n/**\n * Backfill / reconcile the companion column.\n *\n * Denormalized-on-write columns go stale when writes bypass hooks (bulk\n * import, direct migration) and are empty for rows that predate the switch\n * being enabled. This scans every object that carries the companion column\n * (paged, system context) and fills the gaps; with `force: true` it\n * recomputes unconditionally (the periodic reconcile / rebuild entry).\n * Idempotent; per-row failures are skipped so one bad row never aborts the\n * pass.\n */\nexport async function backfillSearchCompanion(\n engine: MinimalEngine,\n logger?: MinimalLogger,\n options?: CompanionBackfillOptions,\n): Promise<CompanionBackfillResult> {\n const batchSize = Math.max(1, options?.batchSize ?? 1000);\n const all = options?.object\n ? [engine.registry?.getObject?.(options.object)].filter(Boolean)\n : engine.registry?.getAllObjects?.() ?? [];\n\n const result: CompanionBackfillResult = { objects: 0, scanned: 0, updated: 0 };\n\n for (const schema of all) {\n if (!schema?.name || !schema?.fields?.[SEARCH_COMPANION_FIELD]) continue;\n const sources = resolveSearchCompanionSources(schema);\n if (sources.length === 0) continue;\n result.objects++;\n\n let offset = 0;\n for (;;) {\n let rows: any[] = [];\n try {\n rows = await engine.find(schema.name, {\n fields: ['id', ...sources, SEARCH_COMPANION_FIELD],\n limit: batchSize,\n offset,\n context: SYSTEM_CTX,\n });\n } catch (err: any) {\n logger?.warn?.('[pinyin-search] backfill scan failed', { object: schema.name, error: err?.message });\n break;\n }\n if (!rows?.length) break;\n result.scanned += rows.length;\n\n for (const row of rows) {\n if (row?.id == null) continue;\n const hasBlob = typeof row[SEARCH_COMPANION_FIELD] === 'string' && row[SEARCH_COMPANION_FIELD] !== '';\n const hasCjkSource = sources.some((s) => containsCJK(row[s]));\n // Backfill mode: touch only rows missing a blob they should have.\n // Force mode: recompute everything (also clears stale blobs).\n if (!options?.force && (hasBlob || !hasCjkSource)) continue;\n try {\n const value = await computeSearchCompanionValue(sources.map((s) => row[s]));\n if (!options?.force && value == null) continue;\n if (value === row[SEARCH_COMPANION_FIELD]) continue;\n await engine.update(\n schema.name,\n { id: row.id, [SEARCH_COMPANION_FIELD]: value },\n { context: SYSTEM_CTX },\n );\n result.updated++;\n } catch (err: any) {\n logger?.warn?.('[pinyin-search] backfill row skipped', {\n object: schema.name,\n id: row.id,\n error: err?.message,\n });\n }\n }\n\n if (rows.length < batchSize) break;\n offset += batchSize;\n }\n }\n\n if (result.updated > 0) {\n logger?.info?.('[pinyin-search] companion backfill complete', result);\n }\n return result;\n}\n\n/**\n * Periodic reconcile / rebuild entry: recompute the companion for every row\n * (optionally one object). Alias for `backfillSearchCompanion` with\n * `force: true` — exposed under its own name so operators/jobs have an\n * explicit \"rebuild the pinyin index\" handle.\n */\nexport function rebuildSearchCompanion(\n engine: MinimalEngine,\n logger?: MinimalLogger,\n options?: Omit<CompanionBackfillOptions, 'force'>,\n): Promise<CompanionBackfillResult> {\n return backfillSearchCompanion(engine, logger, { ...options, force: true });\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Pinyin normalization for the `__search` companion column (#2486).\n *\n * One normalized blob per record — full pinyin AND initials in the same\n * column — so a single `$contains` recalls every latin input shape:\n *\n * \"张伟\" → \"zhangwei zw\"\n * `zhang` / `wei` / `zhangwei` → substring of the full form\n * `zw` → substring of the initials form\n *\n * `pinyin-pro` is loaded lazily on first use: non-Chinese deployments (flag\n * off → hooks never bound) never import it and pay zero cost.\n *\n * Polyphones: pinyin-pro's default heuristics are accepted (issue #2486\n * \"待定\" — surname polyphone dictionaries are a P2 follow-up).\n */\n\nimport { containsCJK } from '@objectstack/objectql';\n\ntype PinyinFn = (text: string, options?: Record<string, unknown>) => string | string[];\n\nlet _pinyin: Promise<PinyinFn> | null = null;\n\n/** Lazy-load `pinyin-pro` (cached module-wide). */\nfunction loadPinyin(): Promise<PinyinFn> {\n _pinyin ??= import('pinyin-pro').then((m: any) => (m.pinyin ?? m.default?.pinyin) as PinyinFn);\n return _pinyin;\n}\n\n/** Lowercase and strip everything that is not a latin letter or digit. */\nfunction squash(syllables: string | string[]): string {\n const joined = Array.isArray(syllables) ? syllables.join('') : String(syllables ?? '');\n return joined.toLowerCase().replace(/[^a-z0-9]+/g, '');\n}\n\n/**\n * Compute the companion value for the given source-field values.\n *\n * Returns the normalized blob (`\"<full-pinyin> <initials>\"`, deduplicated)\n * when at least one value contains CJK characters, else `null` — a `null`\n * companion means \"nothing pinyin-searchable here\" and clears any stale blob\n * when a name is edited away from CJK. Non-CJK values need no companion:\n * their source column already matches latin input directly.\n */\nexport async function computeSearchCompanionValue(values: ReadonlyArray<unknown>): Promise<string | null> {\n const cjkValues = values.filter((v): v is string => containsCJK(v));\n if (cjkValues.length === 0) return null;\n\n const pinyin = await loadPinyin();\n const parts: string[] = [];\n for (const value of cjkValues) {\n // `nonZh: 'consecutive'` keeps latin/digit runs intact inside mixed\n // values (\"张伟2号\" → \"zhangwei2hao\"), so mixed names stay one token.\n const full = squash(pinyin(value, { toneType: 'none', type: 'array', nonZh: 'consecutive' }));\n const initials = squash(pinyin(value, { pattern: 'first', toneType: 'none', type: 'array', nonZh: 'consecutive' }));\n if (full) parts.push(full);\n if (initials && initials !== full) parts.push(initials);\n }\n if (parts.length === 0) return null;\n return [...new Set(parts)].join(' ');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBA,mBAA2C;;;ACH3C,IAAAA,mBAIO;;;ACHP,sBAA4B;AAI5B,IAAI,UAAoC;AAGxC,SAAS,aAAgC;AACvC,wBAAY,OAAO,YAAY,EAAE,KAAK,CAAC,MAAY,EAAE,UAAU,EAAE,SAAS,MAAmB;AAC7F,SAAO;AACT;AAGA,SAAS,OAAO,WAAsC;AACpD,QAAM,SAAS,MAAM,QAAQ,SAAS,IAAI,UAAU,KAAK,EAAE,IAAI,OAAO,aAAa,EAAE;AACrF,SAAO,OAAO,YAAY,EAAE,QAAQ,eAAe,EAAE;AACvD;AAWA,eAAsB,4BAA4B,QAAwD;AACxG,QAAM,YAAY,OAAO,OAAO,CAAC,UAAmB,6BAAY,CAAC,CAAC;AAClE,MAAI,UAAU,WAAW,EAAG,QAAO;AAEnC,QAAM,SAAS,MAAM,WAAW;AAChC,QAAM,QAAkB,CAAC;AACzB,aAAW,SAAS,WAAW;AAG7B,UAAM,OAAO,OAAO,OAAO,OAAO,EAAE,UAAU,QAAQ,MAAM,SAAS,OAAO,cAAc,CAAC,CAAC;AAC5F,UAAM,WAAW,OAAO,OAAO,OAAO,EAAE,SAAS,SAAS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YAAY;AACnC,YAAM,SAAS,KAAK,cAAc,GAAG;AACrC,UAAI,CAAC,QAAQ;AACX,YAAI,OAAO,KAAK,yEAAoE;AACpF;AAAA,MACF;AACA,UAAI;AACF,iCAAyB,QAAQ,IAAI,MAAa;AAAA,MACpD,SAAS,KAAU;AACjB,YAAI,OAAO,KAAK,iDAAiD,EAAE,OAAO,KAAK,QAAQ,CAAC;AAAA,MAC1F;AAAA,IACF,CAAC;AAKD,QAAI,KAAK,QAAQ,aAAa,OAAO;AACnC,UAAI,KAAK,uBAAuB,YAAY;AAC1C,cAAM,SAAS,KAAK,cAAc,GAAG;AACrC,YAAI,CAAC,OAAQ;AACb,YAAI;AACF,gBAAM,wBAAwB,QAAQ,IAAI,MAAa;AAAA,QACzD,SAAS,KAAU;AACjB,cAAI,OAAO,KAAK,iDAAiD,EAAE,OAAO,KAAK,QAAQ,CAAC;AAAA,QAC1F;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEQ,cAAc,KAAyB;AAC7C,QAAI;AACF,aAAO,IAAI,WAAgB,UAAU;AAAA,IACvC,QAAQ;AACN,UAAI;AACF,eAAO,IAAI,WAAgB,MAAM;AAAA,MACnC,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;","names":["import_objectql"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/pinyin-search-plugin.ts","../src/companion-projection.ts","../src/pinyin.ts"],"sourcesContent":["// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport { PinyinSearchPlugin } from './pinyin-search-plugin.js';\nexport type { PinyinSearchPluginOptions } from './pinyin-search-plugin.js';\nexport {\n bindSearchCompanionHooks,\n backfillSearchCompanion,\n rebuildSearchCompanion,\n PINYIN_SEARCH_HOOK_PACKAGE,\n} from './companion-projection.js';\nexport type {\n CompanionBackfillOptions,\n CompanionBackfillResult,\n} from './companion-projection.js';\nexport { computeSearchCompanionValue } from './pinyin.js';\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * PinyinSearchPlugin (#2486) — pinyin recall for `$search`.\n *\n * Pure hook plugin: the `__search` companion column is declared at object\n * compile time by the SchemaRegistry (gated on the SAME\n * `OS_SEARCH_PINYIN_ENABLED` decision point), the engine ORs it into the\n * `$search` filter, and this plugin fills the value:\n *\n * - before-save hooks: recompute full pinyin + initials of the\n * display/name field when it changes;\n * - boot backfill (`kernel:bootstrapped`): fill rows that predate the\n * switch or arrived via hook-bypassing writes;\n * - `rebuildSearchCompanion` (exported): explicit reconcile/rebuild entry.\n *\n * When the flag is off the plugin is inert: no hooks, no backfill, and\n * `pinyin-pro` is never imported.\n */\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport { resolveSearchPinyinEnabled } from '@objectstack/types';\nimport {\n bindSearchCompanionHooks,\n backfillSearchCompanion,\n} from './companion-projection.js';\n\nexport interface PinyinSearchPluginOptions {\n /**\n * Force-enable/disable regardless of `OS_SEARCH_PINYIN_ENABLED` (tests /\n * embedders). Default: `resolveSearchPinyinEnabled()`.\n */\n enabled?: boolean;\n /** Skip the boot backfill (default: run it once per boot). */\n backfill?: boolean;\n}\n\nexport class PinyinSearchPlugin implements Plugin {\n name = 'com.objectstack.plugin.pinyin-search';\n version = '1.0.0';\n type = 'standard';\n dependencies = ['com.objectstack.engine.objectql'];\n\n private readonly options: PinyinSearchPluginOptions;\n\n constructor(options: PinyinSearchPluginOptions = {}) {\n this.options = options;\n }\n\n private get enabled(): boolean {\n return this.options.enabled ?? resolveSearchPinyinEnabled();\n }\n\n async init(_ctx: PluginContext): Promise<void> {\n // Nothing to register: the companion column is provisioned by the\n // SchemaRegistry's compile-time seam, not injected at runtime.\n }\n\n async start(ctx: PluginContext): Promise<void> {\n if (!this.enabled) {\n ctx.logger.debug?.('PinyinSearchPlugin: OS_SEARCH_PINYIN_ENABLED is off — inert');\n return;\n }\n\n ctx.hook('kernel:ready', async () => {\n const engine = this.resolveEngine(ctx);\n if (!engine) {\n ctx.logger.warn('PinyinSearchPlugin: no ObjectQL engine — companion hooks NOT bound');\n return;\n }\n try {\n bindSearchCompanionHooks(engine, ctx.logger as any);\n } catch (err: any) {\n ctx.logger.warn('PinyinSearchPlugin: companion hooks not bound', { error: err?.message });\n }\n });\n\n // Backfill AFTER boot settles (`kernel:bootstrapped` fires once every\n // `kernel:ready` hook — including seed loading — has completed), so\n // seeded rows written before/around hook binding are reconciled too.\n if (this.options.backfill !== false) {\n ctx.hook('kernel:bootstrapped', async () => {\n const engine = this.resolveEngine(ctx);\n if (!engine) return;\n try {\n await backfillSearchCompanion(engine, ctx.logger as any);\n } catch (err: any) {\n ctx.logger.warn('PinyinSearchPlugin: companion backfill failed', { error: err?.message });\n }\n });\n }\n }\n\n private resolveEngine(ctx: PluginContext): any {\n try {\n return ctx.getService<any>('objectql');\n } catch {\n try {\n return ctx.getService<any>('data');\n } catch {\n return null;\n }\n }\n }\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * `__search` companion-column projection (#2486).\n *\n * The column itself is DECLARED at object compile time by the SchemaRegistry\n * (`provisionSearchCompanion`, gated on `OS_SEARCH_PINYIN_ENABLED`); this\n * module only FILLS the value — the `plugin-sharing` primary-BU projection\n * pattern (column on the object, plugin maintains it via hooks).\n *\n * Write path: global `beforeInsert`/`beforeUpdate` hooks stamp\n * `data.__search` whenever a companion source field (the object's\n * display/name field) is present in the write — i.e. only when the source\n * actually changed, avoiding write amplification. Writes that bypass hooks\n * (bulk import, direct migration) leave the companion empty; the boot\n * backfill and the `rebuildSearchCompanion` reconcile entry cover that.\n */\n\nimport {\n SEARCH_COMPANION_FIELD,\n resolveSearchCompanionSources,\n containsCJK,\n} from '@objectstack/objectql';\nimport { keysetWalk } from '@objectstack/types';\nimport { computeSearchCompanionValue } from './pinyin.js';\n\nconst SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const;\n\nexport const PINYIN_SEARCH_HOOK_PACKAGE = 'plugin-pinyin-search:companion';\n\ninterface MinimalEngine {\n registerHook(\n event: string,\n handler: (ctx: any) => any | Promise<any>,\n options?: { object?: string | string[]; priority?: number; packageId?: string },\n ): void;\n unregisterHooksByPackage(packageId: string): number;\n find(object: string, query?: any, options?: any): Promise<any[]>;\n update(object: string, data: any, options?: any): Promise<any>;\n registry?: {\n getObject(name: string): any;\n getAllObjects?(packageId?: string): any[];\n };\n}\n\ninterface MinimalLogger {\n info?: (msg: any, ...rest: any[]) => void;\n warn?: (msg: any, ...rest: any[]) => void;\n debug?: (msg: any, ...rest: any[]) => void;\n}\n\n/**\n * Stamp `data.__search` on a before-save hook context when a companion source\n * field is part of the write. Recomputes from the NEW value; a non-CJK new\n * value clears the companion (null) so stale pinyin never recalls a renamed\n * record. Never throws — a normalization failure must not fail the write.\n */\nasync function stampCompanion(engine: MinimalEngine, ctx: any, logger?: MinimalLogger): Promise<void> {\n const object = ctx?.object;\n if (!object) return;\n const schema = engine.registry?.getObject?.(object);\n if (!schema?.fields?.[SEARCH_COMPANION_FIELD]) return;\n\n const data = ctx?.input?.data;\n if (!data || typeof data !== 'object' || Array.isArray(data)) return;\n\n const sources = resolveSearchCompanionSources(schema);\n if (sources.length === 0) return;\n const touched = sources.filter((s) => Object.prototype.hasOwnProperty.call(data, s));\n if (touched.length === 0) return; // source unchanged → no recompute (no write amplification)\n\n try {\n data[SEARCH_COMPANION_FIELD] = await computeSearchCompanionValue(sources.map((s) => data[s]));\n } catch (err: any) {\n logger?.warn?.('[pinyin-search] companion normalization failed — write proceeds without it', {\n object,\n error: err?.message,\n });\n }\n}\n\n/**\n * Bind the global before-save hooks that keep `__search` in step. Idempotent\n * (unbinds the package first). Hooks are global (no object filter) with a\n * cheap early-out: objects without a provisioned companion column return\n * immediately. They run for system-context writes too — the projection must\n * stay correct regardless of who writes (seeds, imports, admin UI).\n */\nexport function bindSearchCompanionHooks(engine: MinimalEngine, logger?: MinimalLogger): void {\n if (typeof engine.registerHook !== 'function') return;\n if (typeof engine.unregisterHooksByPackage === 'function') {\n engine.unregisterHooksByPackage(PINYIN_SEARCH_HOOK_PACKAGE);\n }\n const opts = { packageId: PINYIN_SEARCH_HOOK_PACKAGE, priority: 150 };\n const handler = (ctx: any) => stampCompanion(engine, ctx, logger);\n engine.registerHook('beforeInsert', handler, opts);\n engine.registerHook('beforeUpdate', handler, opts);\n logger?.info?.('[pinyin-search] companion hooks bound (beforeInsert/beforeUpdate, all objects)');\n}\n\nexport interface CompanionBackfillOptions {\n /** Rows fetched per page during the scan. Default 1000. */\n batchSize?: number;\n /** Restrict to one object (reconcile entry); default: every provisioned object. */\n object?: string;\n /**\n * Recompute EVERY row's companion, not just missing ones — the periodic\n * reconcile/rebuild mode. Default false (backfill: only rows whose\n * companion is empty but whose source has CJK content).\n */\n force?: boolean;\n}\n\nexport interface CompanionBackfillResult {\n objects: number;\n scanned: number;\n updated: number;\n}\n\n/**\n * Backfill / reconcile the companion column.\n *\n * Denormalized-on-write columns go stale when writes bypass hooks (bulk\n * import, direct migration) and are empty for rows that predate the switch\n * being enabled. This scans every object that carries the companion column\n * (paged, system context) and fills the gaps; with `force: true` it\n * recomputes unconditionally (the periodic reconcile / rebuild entry).\n * Idempotent; per-row failures are skipped so one bad row never aborts the\n * pass.\n */\nexport async function backfillSearchCompanion(\n engine: MinimalEngine,\n logger?: MinimalLogger,\n options?: CompanionBackfillOptions,\n): Promise<CompanionBackfillResult> {\n const batchSize = Math.max(1, options?.batchSize ?? 1000);\n const all = options?.object\n ? [engine.registry?.getObject?.(options.object)].filter(Boolean)\n : engine.registry?.getAllObjects?.() ?? [];\n\n const result: CompanionBackfillResult = { objects: 0, scanned: 0, updated: 0 };\n\n for (const schema of all) {\n if (!schema?.name || !schema?.fields?.[SEARCH_COMPANION_FIELD]) continue;\n const sources = resolveSearchCompanionSources(schema);\n if (sources.length === 0) continue;\n result.objects++;\n\n // Seek by `id` (#4363). This walk UPDATES the rows it reads, and an offset\n // counts into a set those writes are changing, so rows slide past the\n // cursor and never get their companion blob — a backfill that reports a\n // clean pass while leaving records unsearchable.\n const walk = keysetWalk<any>(\n (q) => engine.find(schema.name, {\n ...q,\n fields: ['id', ...sources, SEARCH_COMPANION_FIELD],\n context: SYSTEM_CTX,\n }),\n { pageSize: batchSize },\n );\n\n try {\n for await (const rows of walk.pages()) {\n result.scanned += rows.length;\n\n for (const row of rows) {\n if (row?.id == null) continue;\n const hasBlob = typeof row[SEARCH_COMPANION_FIELD] === 'string' && row[SEARCH_COMPANION_FIELD] !== '';\n const hasCjkSource = sources.some((s) => containsCJK(row[s]));\n // Backfill mode: touch only rows missing a blob they should have.\n // Force mode: recompute everything (also clears stale blobs).\n if (!options?.force && (hasBlob || !hasCjkSource)) continue;\n try {\n const value = await computeSearchCompanionValue(sources.map((s) => row[s]));\n if (!options?.force && value == null) continue;\n if (value === row[SEARCH_COMPANION_FIELD]) continue;\n await engine.update(\n schema.name,\n { id: row.id, [SEARCH_COMPANION_FIELD]: value },\n { context: SYSTEM_CTX },\n );\n result.updated++;\n } catch (err: any) {\n logger?.warn?.('[pinyin-search] backfill row skipped', {\n object: schema.name,\n id: row.id,\n error: err?.message,\n });\n }\n }\n }\n } catch (err: any) {\n logger?.warn?.('[pinyin-search] backfill scan failed', { object: schema.name, error: err?.message });\n continue;\n }\n }\n\n if (result.updated > 0) {\n logger?.info?.('[pinyin-search] companion backfill complete', result);\n }\n return result;\n}\n\n/**\n * Periodic reconcile / rebuild entry: recompute the companion for every row\n * (optionally one object). Alias for `backfillSearchCompanion` with\n * `force: true` — exposed under its own name so operators/jobs have an\n * explicit \"rebuild the pinyin index\" handle.\n */\nexport function rebuildSearchCompanion(\n engine: MinimalEngine,\n logger?: MinimalLogger,\n options?: Omit<CompanionBackfillOptions, 'force'>,\n): Promise<CompanionBackfillResult> {\n return backfillSearchCompanion(engine, logger, { ...options, force: true });\n}\n","// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Pinyin normalization for the `__search` companion column (#2486).\n *\n * One normalized blob per record — full pinyin AND initials in the same\n * column — so a single `$contains` recalls every latin input shape:\n *\n * \"张伟\" → \"zhangwei zw\"\n * `zhang` / `wei` / `zhangwei` → substring of the full form\n * `zw` → substring of the initials form\n *\n * `pinyin-pro` is loaded lazily on first use: non-Chinese deployments (flag\n * off → hooks never bound) never import it and pay zero cost.\n *\n * Polyphones: pinyin-pro's default heuristics are accepted (issue #2486\n * \"待定\" — surname polyphone dictionaries are a P2 follow-up).\n */\n\nimport { containsCJK } from '@objectstack/objectql';\n\ntype PinyinFn = (text: string, options?: Record<string, unknown>) => string | string[];\n\nlet _pinyin: Promise<PinyinFn> | null = null;\n\n/** Lazy-load `pinyin-pro` (cached module-wide). */\nfunction loadPinyin(): Promise<PinyinFn> {\n _pinyin ??= import('pinyin-pro').then((m: any) => (m.pinyin ?? m.default?.pinyin) as PinyinFn);\n return _pinyin;\n}\n\n/** Lowercase and strip everything that is not a latin letter or digit. */\nfunction squash(syllables: string | string[]): string {\n const joined = Array.isArray(syllables) ? syllables.join('') : String(syllables ?? '');\n return joined.toLowerCase().replace(/[^a-z0-9]+/g, '');\n}\n\n/**\n * Compute the companion value for the given source-field values.\n *\n * Returns the normalized blob (`\"<full-pinyin> <initials>\"`, deduplicated)\n * when at least one value contains CJK characters, else `null` — a `null`\n * companion means \"nothing pinyin-searchable here\" and clears any stale blob\n * when a name is edited away from CJK. Non-CJK values need no companion:\n * their source column already matches latin input directly.\n */\nexport async function computeSearchCompanionValue(values: ReadonlyArray<unknown>): Promise<string | null> {\n const cjkValues = values.filter((v): v is string => containsCJK(v));\n if (cjkValues.length === 0) return null;\n\n const pinyin = await loadPinyin();\n const parts: string[] = [];\n for (const value of cjkValues) {\n // `nonZh: 'consecutive'` keeps latin/digit runs intact inside mixed\n // values (\"张伟2号\" → \"zhangwei2hao\"), so mixed names stay one token.\n const full = squash(pinyin(value, { toneType: 'none', type: 'array', nonZh: 'consecutive' }));\n const initials = squash(pinyin(value, { pattern: 'first', toneType: 'none', type: 'array', nonZh: 'consecutive' }));\n if (full) parts.push(full);\n if (initials && initials !== full) parts.push(initials);\n }\n if (parts.length === 0) return null;\n return [...new Set(parts)].join(' ');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBA,IAAAA,gBAA2C;;;ACH3C,IAAAC,mBAIO;AACP,mBAA2B;;;ACJ3B,sBAA4B;AAI5B,IAAI,UAAoC;AAGxC,SAAS,aAAgC;AACvC,wBAAY,OAAO,YAAY,EAAE,KAAK,CAAC,MAAY,EAAE,UAAU,EAAE,SAAS,MAAmB;AAC7F,SAAO;AACT;AAGA,SAAS,OAAO,WAAsC;AACpD,QAAM,SAAS,MAAM,QAAQ,SAAS,IAAI,UAAU,KAAK,EAAE,IAAI,OAAO,aAAa,EAAE;AACrF,SAAO,OAAO,YAAY,EAAE,QAAQ,eAAe,EAAE;AACvD;AAWA,eAAsB,4BAA4B,QAAwD;AACxG,QAAM,YAAY,OAAO,OAAO,CAAC,UAAmB,6BAAY,CAAC,CAAC;AAClE,MAAI,UAAU,WAAW,EAAG,QAAO;AAEnC,QAAM,SAAS,MAAM,WAAW;AAChC,QAAM,QAAkB,CAAC;AACzB,aAAW,SAAS,WAAW;AAG7B,UAAM,OAAO,OAAO,OAAO,OAAO,EAAE,UAAU,QAAQ,MAAM,SAAS,OAAO,cAAc,CAAC,CAAC;AAC5F,UAAM,WAAW,OAAO,OAAO,OAAO,EAAE,SAAS,SAAS,UAAU,QAAQ,MAAM,SAAS,OAAO,cAAc,CAAC,CAAC;AAClH,QAAI,KAAM,OAAM,KAAK,IAAI;AACzB,QAAI,YAAY,aAAa,KAAM,OAAM,KAAK,QAAQ;AAAA,EACxD;AACA,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,SAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,EAAE,KAAK,GAAG;AACrC;;;ADpCA,IAAM,aA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Aa,OAAO;AACnC,UAAI,KAAK,uBAAuB,YAAY;AAC1C,cAAM,SAAS,KAAK,cAAc,GAAG;AACrC,YAAI,CAAC,OAAQ;AACb,YAAI;AACF,gBAAM,wBAAwB,QAAQ,IAAI,MAAa;AAAA,QACzD,SAAS,KAAU;AACjB,cAAI,OAAO,KAAK,iDAAiD,EAAE,OAAO,KAAK,QAAQ,CAAC;AAAA,QAC1F;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEQ,cAAc,KAAyB;AAC7C,QAAI;AACF,aAAO,IAAI,WAAgB,UAAU;AAAA,IACvC,QAAQ;AACN,UAAI;AACF,eAAO,IAAI,WAAgB,MAAM;AAAA,MACnC,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;","names":["import_types","import_objectql"]}
package/dist/index.mjs CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  resolveSearchCompanionSources,
8
8
  containsCJK as containsCJK2
9
9
  } from "@objectstack/objectql";
10
+ import { keysetWalk } from "@objectstack/types";
10
11
 
11
12
  // src/pinyin.ts
12
13
  import { containsCJK } from "@objectstack/objectql";
@@ -77,47 +78,44 @@ async function backfillSearchCompanion(engine, logger, options) {
77
78
  const sources = resolveSearchCompanionSources(schema);
78
79
  if (sources.length === 0) continue;
79
80
  result.objects++;
80
- let offset = 0;
81
- for (; ; ) {
82
- let rows = [];
83
- try {
84
- rows = await engine.find(schema.name, {
85
- fields: ["id", ...sources, SEARCH_COMPANION_FIELD],
86
- limit: batchSize,
87
- offset,
88
- context: SYSTEM_CTX
89
- });
90
- } catch (err) {
91
- logger?.warn?.("[pinyin-search] backfill scan failed", { object: schema.name, error: err?.message });
92
- break;
93
- }
94
- if (!rows?.length) break;
95
- result.scanned += rows.length;
96
- for (const row of rows) {
97
- if (row?.id == null) continue;
98
- const hasBlob = typeof row[SEARCH_COMPANION_FIELD] === "string" && row[SEARCH_COMPANION_FIELD] !== "";
99
- const hasCjkSource = sources.some((s) => containsCJK2(row[s]));
100
- if (!options?.force && (hasBlob || !hasCjkSource)) continue;
101
- try {
102
- const value = await computeSearchCompanionValue(sources.map((s) => row[s]));
103
- if (!options?.force && value == null) continue;
104
- if (value === row[SEARCH_COMPANION_FIELD]) continue;
105
- await engine.update(
106
- schema.name,
107
- { id: row.id, [SEARCH_COMPANION_FIELD]: value },
108
- { context: SYSTEM_CTX }
109
- );
110
- result.updated++;
111
- } catch (err) {
112
- logger?.warn?.("[pinyin-search] backfill row skipped", {
113
- object: schema.name,
114
- id: row.id,
115
- error: err?.message
116
- });
81
+ const walk = keysetWalk(
82
+ (q) => engine.find(schema.name, {
83
+ ...q,
84
+ fields: ["id", ...sources, SEARCH_COMPANION_FIELD],
85
+ context: SYSTEM_CTX
86
+ }),
87
+ { pageSize: batchSize }
88
+ );
89
+ try {
90
+ for await (const rows of walk.pages()) {
91
+ result.scanned += rows.length;
92
+ for (const row of rows) {
93
+ if (row?.id == null) continue;
94
+ const hasBlob = typeof row[SEARCH_COMPANION_FIELD] === "string" && row[SEARCH_COMPANION_FIELD] !== "";
95
+ const hasCjkSource = sources.some((s) => containsCJK2(row[s]));
96
+ if (!options?.force && (hasBlob || !hasCjkSource)) continue;
97
+ try {
98
+ const value = await computeSearchCompanionValue(sources.map((s) => row[s]));
99
+ if (!options?.force && value == null) continue;
100
+ if (value === row[SEARCH_COMPANION_FIELD]) continue;
101
+ await engine.update(
102
+ schema.name,
103
+ { id: row.id, [SEARCH_COMPANION_FIELD]: value },
104
+ { context: SYSTEM_CTX }
105
+ );
106
+ result.updated++;
107
+ } catch (err) {
108
+ logger?.warn?.("[pinyin-search] backfill row skipped", {
109
+ object: schema.name,
110
+ id: row.id,
111
+ error: err?.message
112
+ });
113
+ }
117
114
  }
118
115
  }
119
- if (rows.length < batchSize) break;
120
- offset += batchSize;
116
+ } catch (err) {
117
+ logger?.warn?.("[pinyin-search] backfill scan failed", { object: schema.name, error: err?.message });
118
+ continue;
121
119
  }
122
120
  }
123
121
  if (result.updated > 0) {