@objectstack/plugin-pinyin-search 15.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,233 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ PINYIN_SEARCH_HOOK_PACKAGE: () => PINYIN_SEARCH_HOOK_PACKAGE,
34
+ PinyinSearchPlugin: () => PinyinSearchPlugin,
35
+ backfillSearchCompanion: () => backfillSearchCompanion,
36
+ bindSearchCompanionHooks: () => bindSearchCompanionHooks,
37
+ computeSearchCompanionValue: () => computeSearchCompanionValue,
38
+ rebuildSearchCompanion: () => rebuildSearchCompanion
39
+ });
40
+ module.exports = __toCommonJS(index_exports);
41
+
42
+ // src/pinyin-search-plugin.ts
43
+ var import_types = require("@objectstack/types");
44
+
45
+ // src/companion-projection.ts
46
+ var import_objectql2 = require("@objectstack/objectql");
47
+
48
+ // src/pinyin.ts
49
+ var import_objectql = require("@objectstack/objectql");
50
+ var _pinyin = null;
51
+ function loadPinyin() {
52
+ _pinyin ?? (_pinyin = import("pinyin-pro").then((m) => m.pinyin ?? m.default?.pinyin));
53
+ return _pinyin;
54
+ }
55
+ function squash(syllables) {
56
+ const joined = Array.isArray(syllables) ? syllables.join("") : String(syllables ?? "");
57
+ return joined.toLowerCase().replace(/[^a-z0-9]+/g, "");
58
+ }
59
+ async function computeSearchCompanionValue(values) {
60
+ const cjkValues = values.filter((v) => (0, import_objectql.containsCJK)(v));
61
+ if (cjkValues.length === 0) return null;
62
+ const pinyin = await loadPinyin();
63
+ const parts = [];
64
+ for (const value of cjkValues) {
65
+ const full = squash(pinyin(value, { toneType: "none", type: "array", nonZh: "consecutive" }));
66
+ const initials = squash(pinyin(value, { pattern: "first", toneType: "none", type: "array", nonZh: "consecutive" }));
67
+ if (full) parts.push(full);
68
+ if (initials && initials !== full) parts.push(initials);
69
+ }
70
+ if (parts.length === 0) return null;
71
+ return [...new Set(parts)].join(" ");
72
+ }
73
+
74
+ // src/companion-projection.ts
75
+ var SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] };
76
+ var PINYIN_SEARCH_HOOK_PACKAGE = "plugin-pinyin-search:companion";
77
+ async function stampCompanion(engine, ctx, logger) {
78
+ const object = ctx?.object;
79
+ if (!object) return;
80
+ const schema = engine.registry?.getObject?.(object);
81
+ if (!schema?.fields?.[import_objectql2.SEARCH_COMPANION_FIELD]) return;
82
+ const data = ctx?.input?.data;
83
+ if (!data || typeof data !== "object" || Array.isArray(data)) return;
84
+ const sources = (0, import_objectql2.resolveSearchCompanionSources)(schema);
85
+ if (sources.length === 0) return;
86
+ const touched = sources.filter((s) => Object.prototype.hasOwnProperty.call(data, s));
87
+ if (touched.length === 0) return;
88
+ try {
89
+ data[import_objectql2.SEARCH_COMPANION_FIELD] = await computeSearchCompanionValue(sources.map((s) => data[s]));
90
+ } catch (err) {
91
+ logger?.warn?.("[pinyin-search] companion normalization failed \u2014 write proceeds without it", {
92
+ object,
93
+ error: err?.message
94
+ });
95
+ }
96
+ }
97
+ function bindSearchCompanionHooks(engine, logger) {
98
+ if (typeof engine.registerHook !== "function") return;
99
+ if (typeof engine.unregisterHooksByPackage === "function") {
100
+ engine.unregisterHooksByPackage(PINYIN_SEARCH_HOOK_PACKAGE);
101
+ }
102
+ const opts = { packageId: PINYIN_SEARCH_HOOK_PACKAGE, priority: 150 };
103
+ const handler = (ctx) => stampCompanion(engine, ctx, logger);
104
+ engine.registerHook("beforeInsert", handler, opts);
105
+ engine.registerHook("beforeUpdate", handler, opts);
106
+ logger?.info?.("[pinyin-search] companion hooks bound (beforeInsert/beforeUpdate, all objects)");
107
+ }
108
+ async function backfillSearchCompanion(engine, logger, options) {
109
+ const batchSize = Math.max(1, options?.batchSize ?? 1e3);
110
+ const all = options?.object ? [engine.registry?.getObject?.(options.object)].filter(Boolean) : engine.registry?.getAllObjects?.() ?? [];
111
+ const result = { objects: 0, scanned: 0, updated: 0 };
112
+ for (const schema of all) {
113
+ if (!schema?.name || !schema?.fields?.[import_objectql2.SEARCH_COMPANION_FIELD]) continue;
114
+ const sources = (0, import_objectql2.resolveSearchCompanionSources)(schema);
115
+ if (sources.length === 0) continue;
116
+ 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
+ });
154
+ }
155
+ }
156
+ if (rows.length < batchSize) break;
157
+ offset += batchSize;
158
+ }
159
+ }
160
+ if (result.updated > 0) {
161
+ logger?.info?.("[pinyin-search] companion backfill complete", result);
162
+ }
163
+ return result;
164
+ }
165
+ function rebuildSearchCompanion(engine, logger, options) {
166
+ return backfillSearchCompanion(engine, logger, { ...options, force: true });
167
+ }
168
+
169
+ // src/pinyin-search-plugin.ts
170
+ var PinyinSearchPlugin = class {
171
+ constructor(options = {}) {
172
+ this.name = "com.objectstack.plugin.pinyin-search";
173
+ this.version = "1.0.0";
174
+ this.type = "standard";
175
+ this.dependencies = ["com.objectstack.engine.objectql"];
176
+ this.options = options;
177
+ }
178
+ get enabled() {
179
+ return this.options.enabled ?? (0, import_types.resolveSearchPinyinEnabled)();
180
+ }
181
+ async init(_ctx) {
182
+ }
183
+ async start(ctx) {
184
+ if (!this.enabled) {
185
+ ctx.logger.debug?.("PinyinSearchPlugin: OS_SEARCH_PINYIN_ENABLED is off \u2014 inert");
186
+ return;
187
+ }
188
+ ctx.hook("kernel:ready", async () => {
189
+ const engine = this.resolveEngine(ctx);
190
+ if (!engine) {
191
+ ctx.logger.warn("PinyinSearchPlugin: no ObjectQL engine \u2014 companion hooks NOT bound");
192
+ return;
193
+ }
194
+ try {
195
+ bindSearchCompanionHooks(engine, ctx.logger);
196
+ } catch (err) {
197
+ ctx.logger.warn("PinyinSearchPlugin: companion hooks not bound", { error: err?.message });
198
+ }
199
+ });
200
+ if (this.options.backfill !== false) {
201
+ ctx.hook("kernel:bootstrapped", async () => {
202
+ const engine = this.resolveEngine(ctx);
203
+ if (!engine) return;
204
+ try {
205
+ await backfillSearchCompanion(engine, ctx.logger);
206
+ } catch (err) {
207
+ ctx.logger.warn("PinyinSearchPlugin: companion backfill failed", { error: err?.message });
208
+ }
209
+ });
210
+ }
211
+ }
212
+ resolveEngine(ctx) {
213
+ try {
214
+ return ctx.getService("objectql");
215
+ } catch {
216
+ try {
217
+ return ctx.getService("data");
218
+ } catch {
219
+ return null;
220
+ }
221
+ }
222
+ }
223
+ };
224
+ // Annotate the CommonJS export names for ESM import in node:
225
+ 0 && (module.exports = {
226
+ PINYIN_SEARCH_HOOK_PACKAGE,
227
+ PinyinSearchPlugin,
228
+ backfillSearchCompanion,
229
+ bindSearchCompanionHooks,
230
+ computeSearchCompanionValue,
231
+ rebuildSearchCompanion
232
+ });
233
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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,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;;;ADrCA,IAAM,aAAa,EAAE,UAAU,MAAM,WAAW,CAAC,GAAG,aAAa,CAAC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,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"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,195 @@
1
+ // src/pinyin-search-plugin.ts
2
+ import { resolveSearchPinyinEnabled } from "@objectstack/types";
3
+
4
+ // src/companion-projection.ts
5
+ import {
6
+ SEARCH_COMPANION_FIELD,
7
+ resolveSearchCompanionSources,
8
+ containsCJK as containsCJK2
9
+ } from "@objectstack/objectql";
10
+
11
+ // src/pinyin.ts
12
+ import { containsCJK } from "@objectstack/objectql";
13
+ var _pinyin = null;
14
+ function loadPinyin() {
15
+ _pinyin ?? (_pinyin = import("pinyin-pro").then((m) => m.pinyin ?? m.default?.pinyin));
16
+ return _pinyin;
17
+ }
18
+ function squash(syllables) {
19
+ const joined = Array.isArray(syllables) ? syllables.join("") : String(syllables ?? "");
20
+ return joined.toLowerCase().replace(/[^a-z0-9]+/g, "");
21
+ }
22
+ async function computeSearchCompanionValue(values) {
23
+ const cjkValues = values.filter((v) => containsCJK(v));
24
+ if (cjkValues.length === 0) return null;
25
+ const pinyin = await loadPinyin();
26
+ const parts = [];
27
+ for (const value of cjkValues) {
28
+ const full = squash(pinyin(value, { toneType: "none", type: "array", nonZh: "consecutive" }));
29
+ const initials = squash(pinyin(value, { pattern: "first", toneType: "none", type: "array", nonZh: "consecutive" }));
30
+ if (full) parts.push(full);
31
+ if (initials && initials !== full) parts.push(initials);
32
+ }
33
+ if (parts.length === 0) return null;
34
+ return [...new Set(parts)].join(" ");
35
+ }
36
+
37
+ // src/companion-projection.ts
38
+ var SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] };
39
+ var PINYIN_SEARCH_HOOK_PACKAGE = "plugin-pinyin-search:companion";
40
+ async function stampCompanion(engine, ctx, logger) {
41
+ const object = ctx?.object;
42
+ if (!object) return;
43
+ const schema = engine.registry?.getObject?.(object);
44
+ if (!schema?.fields?.[SEARCH_COMPANION_FIELD]) return;
45
+ const data = ctx?.input?.data;
46
+ if (!data || typeof data !== "object" || Array.isArray(data)) return;
47
+ const sources = resolveSearchCompanionSources(schema);
48
+ if (sources.length === 0) return;
49
+ const touched = sources.filter((s) => Object.prototype.hasOwnProperty.call(data, s));
50
+ if (touched.length === 0) return;
51
+ try {
52
+ data[SEARCH_COMPANION_FIELD] = await computeSearchCompanionValue(sources.map((s) => data[s]));
53
+ } catch (err) {
54
+ logger?.warn?.("[pinyin-search] companion normalization failed \u2014 write proceeds without it", {
55
+ object,
56
+ error: err?.message
57
+ });
58
+ }
59
+ }
60
+ function bindSearchCompanionHooks(engine, logger) {
61
+ if (typeof engine.registerHook !== "function") return;
62
+ if (typeof engine.unregisterHooksByPackage === "function") {
63
+ engine.unregisterHooksByPackage(PINYIN_SEARCH_HOOK_PACKAGE);
64
+ }
65
+ const opts = { packageId: PINYIN_SEARCH_HOOK_PACKAGE, priority: 150 };
66
+ const handler = (ctx) => stampCompanion(engine, ctx, logger);
67
+ engine.registerHook("beforeInsert", handler, opts);
68
+ engine.registerHook("beforeUpdate", handler, opts);
69
+ logger?.info?.("[pinyin-search] companion hooks bound (beforeInsert/beforeUpdate, all objects)");
70
+ }
71
+ async function backfillSearchCompanion(engine, logger, options) {
72
+ const batchSize = Math.max(1, options?.batchSize ?? 1e3);
73
+ const all = options?.object ? [engine.registry?.getObject?.(options.object)].filter(Boolean) : engine.registry?.getAllObjects?.() ?? [];
74
+ const result = { objects: 0, scanned: 0, updated: 0 };
75
+ for (const schema of all) {
76
+ if (!schema?.name || !schema?.fields?.[SEARCH_COMPANION_FIELD]) continue;
77
+ const sources = resolveSearchCompanionSources(schema);
78
+ if (sources.length === 0) continue;
79
+ 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
+ });
117
+ }
118
+ }
119
+ if (rows.length < batchSize) break;
120
+ offset += batchSize;
121
+ }
122
+ }
123
+ if (result.updated > 0) {
124
+ logger?.info?.("[pinyin-search] companion backfill complete", result);
125
+ }
126
+ return result;
127
+ }
128
+ function rebuildSearchCompanion(engine, logger, options) {
129
+ return backfillSearchCompanion(engine, logger, { ...options, force: true });
130
+ }
131
+
132
+ // src/pinyin-search-plugin.ts
133
+ var PinyinSearchPlugin = class {
134
+ constructor(options = {}) {
135
+ this.name = "com.objectstack.plugin.pinyin-search";
136
+ this.version = "1.0.0";
137
+ this.type = "standard";
138
+ this.dependencies = ["com.objectstack.engine.objectql"];
139
+ this.options = options;
140
+ }
141
+ get enabled() {
142
+ return this.options.enabled ?? resolveSearchPinyinEnabled();
143
+ }
144
+ async init(_ctx) {
145
+ }
146
+ async start(ctx) {
147
+ if (!this.enabled) {
148
+ ctx.logger.debug?.("PinyinSearchPlugin: OS_SEARCH_PINYIN_ENABLED is off \u2014 inert");
149
+ return;
150
+ }
151
+ ctx.hook("kernel:ready", async () => {
152
+ const engine = this.resolveEngine(ctx);
153
+ if (!engine) {
154
+ ctx.logger.warn("PinyinSearchPlugin: no ObjectQL engine \u2014 companion hooks NOT bound");
155
+ return;
156
+ }
157
+ try {
158
+ bindSearchCompanionHooks(engine, ctx.logger);
159
+ } catch (err) {
160
+ ctx.logger.warn("PinyinSearchPlugin: companion hooks not bound", { error: err?.message });
161
+ }
162
+ });
163
+ if (this.options.backfill !== false) {
164
+ ctx.hook("kernel:bootstrapped", async () => {
165
+ const engine = this.resolveEngine(ctx);
166
+ if (!engine) return;
167
+ try {
168
+ await backfillSearchCompanion(engine, ctx.logger);
169
+ } catch (err) {
170
+ ctx.logger.warn("PinyinSearchPlugin: companion backfill failed", { error: err?.message });
171
+ }
172
+ });
173
+ }
174
+ }
175
+ resolveEngine(ctx) {
176
+ try {
177
+ return ctx.getService("objectql");
178
+ } catch {
179
+ try {
180
+ return ctx.getService("data");
181
+ } catch {
182
+ return null;
183
+ }
184
+ }
185
+ }
186
+ };
187
+ export {
188
+ PINYIN_SEARCH_HOOK_PACKAGE,
189
+ PinyinSearchPlugin,
190
+ backfillSearchCompanion,
191
+ bindSearchCompanionHooks,
192
+ computeSearchCompanionValue,
193
+ rebuildSearchCompanion
194
+ };
195
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../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\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":";AAqBA,SAAS,kCAAkC;;;ACH3C;AAAA,EACE;AAAA,EACA;AAAA,EACA,eAAAA;AAAA,OACK;;;ACHP,SAAS,mBAAmB;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,MAAmB,YAAY,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;;;ADrCA,IAAM,aAAa,EAAE,UAAU,MAAM,WAAW,CAAC,GAAG,aAAa,CAAC,EAAE;AAE7D,IAAM,6BAA6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C,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":["containsCJK","containsCJK"]}
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@objectstack/plugin-pinyin-search",
3
+ "version": "15.1.0",
4
+ "license": "Apache-2.0",
5
+ "description": "Pinyin search recall for ObjectStack — populates the hidden `__search` companion column (full pinyin + initials of the display/name field) so `$search` hits CJK names typed as pinyin. Locale-gated via OS_SEARCH_PINYIN_ENABLED (#2486).",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "dependencies": {
16
+ "pinyin-pro": "^3.28.1",
17
+ "@objectstack/core": "15.1.0",
18
+ "@objectstack/objectql": "15.1.0",
19
+ "@objectstack/types": "15.1.0"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "^26.1.1",
23
+ "typescript": "^6.0.3",
24
+ "vitest": "^4.1.10"
25
+ },
26
+ "keywords": [
27
+ "objectstack",
28
+ "plugin",
29
+ "search",
30
+ "pinyin",
31
+ "i18n"
32
+ ],
33
+ "scripts": {
34
+ "build": "tsup --config ../../../tsup.config.ts",
35
+ "test": "vitest run --passWithNoTests"
36
+ }
37
+ }