@shuo-li/i18n 1.0.4 → 1.0.5

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.
@@ -88,19 +88,10 @@ interface WorkerTask {
88
88
  /** 经 buildParams 映射后的实际请求参数;未提供时 Worker 使用内部字段名 */
89
89
  params?: Record<string, unknown>;
90
90
  }
91
- interface WorkerModuleLoadedMessage {
92
- type: 'moduleLoaded';
93
- storeName: string;
94
- langCode: string;
95
- moduleCode: string;
96
- version: number;
97
- }
98
- interface WorkerDataReadyMessage {
99
- type: 'dataReady';
100
- storeName: string;
101
- storeIndex: number;
102
- record: ResourceRecord;
91
+ interface WorkerRawDataMessage {
92
+ type: 'rawData';
103
93
  task: WorkerTask;
94
+ raw: unknown;
104
95
  }
105
96
  interface WorkerModuleErrorMessage {
106
97
  type: 'moduleError';
@@ -115,7 +106,7 @@ interface WorkerErrorMessage {
115
106
  type: 'error';
116
107
  message?: string;
117
108
  }
118
- type WorkerOutMessage = WorkerModuleLoadedMessage | WorkerDataReadyMessage | WorkerModuleErrorMessage | WorkerDoneMessage | WorkerErrorMessage;
109
+ type WorkerOutMessage = WorkerRawDataMessage | WorkerModuleErrorMessage | WorkerDoneMessage | WorkerErrorMessage;
119
110
  interface WorkerLike {
120
111
  postMessage(data: unknown): void;
121
112
  onMessage(handler: (data: WorkerOutMessage) => void): void;
@@ -88,19 +88,10 @@ interface WorkerTask {
88
88
  /** 经 buildParams 映射后的实际请求参数;未提供时 Worker 使用内部字段名 */
89
89
  params?: Record<string, unknown>;
90
90
  }
91
- interface WorkerModuleLoadedMessage {
92
- type: 'moduleLoaded';
93
- storeName: string;
94
- langCode: string;
95
- moduleCode: string;
96
- version: number;
97
- }
98
- interface WorkerDataReadyMessage {
99
- type: 'dataReady';
100
- storeName: string;
101
- storeIndex: number;
102
- record: ResourceRecord;
91
+ interface WorkerRawDataMessage {
92
+ type: 'rawData';
103
93
  task: WorkerTask;
94
+ raw: unknown;
104
95
  }
105
96
  interface WorkerModuleErrorMessage {
106
97
  type: 'moduleError';
@@ -115,7 +106,7 @@ interface WorkerErrorMessage {
115
106
  type: 'error';
116
107
  message?: string;
117
108
  }
118
- type WorkerOutMessage = WorkerModuleLoadedMessage | WorkerDataReadyMessage | WorkerModuleErrorMessage | WorkerDoneMessage | WorkerErrorMessage;
109
+ type WorkerOutMessage = WorkerRawDataMessage | WorkerModuleErrorMessage | WorkerDoneMessage | WorkerErrorMessage;
119
110
  interface WorkerLike {
120
111
  postMessage(data: unknown): void;
121
112
  onMessage(handler: (data: WorkerOutMessage) => void): void;
@@ -119,6 +119,56 @@ var SSEClient = class {
119
119
  }
120
120
  };
121
121
 
122
+ // src/core/worker-manager.ts
123
+ var WorkerManager = class {
124
+ constructor() {
125
+ this.worker = null;
126
+ this.pendingCallbacks = /* @__PURE__ */ new Set();
127
+ this.finalized = false;
128
+ }
129
+ start(createWorker, payload, callbacks) {
130
+ this.terminate();
131
+ this.finalized = false;
132
+ this.pendingCallbacks = /* @__PURE__ */ new Set();
133
+ if (payload.tasks.length === 0) {
134
+ callbacks.onDone();
135
+ return;
136
+ }
137
+ const worker = createWorker();
138
+ this.worker = worker;
139
+ worker.onMessage((msg) => {
140
+ if (msg.type === "rawData") {
141
+ const p = callbacks.onRawData(msg.task, msg.raw).catch(() => {
142
+ });
143
+ this.pendingCallbacks.add(p);
144
+ p.finally(() => this.pendingCallbacks.delete(p));
145
+ } else if (msg.type === "moduleError") {
146
+ _optionalChain([callbacks, 'access', _7 => _7.onModuleError, 'optionalCall', _8 => _8(msg)]);
147
+ } else if (msg.type === "done" || msg.type === "error") {
148
+ if (msg.type === "error") _optionalChain([callbacks, 'access', _9 => _9.onError, 'optionalCall', _10 => _10()]);
149
+ this.finalize(callbacks);
150
+ }
151
+ });
152
+ worker.postMessage({ type: "start", payload });
153
+ }
154
+ terminate() {
155
+ _optionalChain([this, 'access', _11 => _11.worker, 'optionalAccess', _12 => _12.terminate, 'call', _13 => _13()]);
156
+ this.worker = null;
157
+ }
158
+ isRunning() {
159
+ return this.worker !== null;
160
+ }
161
+ finalize(callbacks) {
162
+ if (this.finalized) return;
163
+ this.finalized = true;
164
+ const pending = [...this.pendingCallbacks];
165
+ Promise.allSettled(pending).then(() => {
166
+ this.terminate();
167
+ callbacks.onDone();
168
+ });
169
+ }
170
+ };
171
+
122
172
  // src/core/utils.ts
123
173
  function buildKey(moduleCode, langCode, store) {
124
174
  return store.cacheGroupKey ? `${moduleCode}_${langCode}_${store.cacheGroupKey}` : `${moduleCode}_${langCode}`;
@@ -162,10 +212,10 @@ function parseI18nValues(values) {
162
212
  }
163
213
  function toDefaultParams(p) {
164
214
  const result = {};
165
- if (_optionalChain([p, 'optionalAccess', _7 => _7.storeName])) result["storeName"] = p.storeName;
166
- if (_optionalChain([p, 'optionalAccess', _8 => _8.langCode])) result["langCode"] = p.langCode;
167
- if (_optionalChain([p, 'optionalAccess', _9 => _9.moduleCode])) result["moduleCode"] = p.moduleCode;
168
- if (_optionalChain([p, 'optionalAccess', _10 => _10.version]) != null) result["version"] = String(p.version);
215
+ if (_optionalChain([p, 'optionalAccess', _14 => _14.storeName])) result["storeName"] = p.storeName;
216
+ if (_optionalChain([p, 'optionalAccess', _15 => _15.langCode])) result["langCode"] = p.langCode;
217
+ if (_optionalChain([p, 'optionalAccess', _16 => _16.moduleCode])) result["moduleCode"] = p.moduleCode;
218
+ if (_optionalChain([p, 'optionalAccess', _17 => _17.version]) != null) result["version"] = String(p.version);
169
219
  return result;
170
220
  }
171
221
  function toQueryString(params) {
@@ -174,89 +224,7 @@ function toQueryString(params) {
174
224
  ).toString();
175
225
  }
176
226
 
177
- // src/core/worker-manager.ts
178
- var WorkerManager = class {
179
- constructor() {
180
- this.worker = null;
181
- this.pendingCallbacks = /* @__PURE__ */ new Set();
182
- this.finalized = false;
183
- }
184
- start(createWorker, payload, callbacks, storage) {
185
- this.terminate();
186
- this.finalized = false;
187
- this.pendingCallbacks = /* @__PURE__ */ new Set();
188
- if (payload.tasks.length === 0) {
189
- callbacks.onDone();
190
- return;
191
- }
192
- const worker = createWorker();
193
- this.worker = worker;
194
- worker.onMessage((msg) => {
195
- if (msg.type === "moduleLoaded") {
196
- const m = msg;
197
- const p = callbacks.onModuleLoaded({
198
- storeName: m.storeName,
199
- langCode: m.langCode,
200
- moduleCode: m.moduleCode,
201
- version: m.version
202
- });
203
- this.pendingCallbacks.add(p);
204
- p.finally(() => this.pendingCallbacks.delete(p));
205
- } else if (msg.type === "dataReady") {
206
- if (!storage) return;
207
- const p = (async () => {
208
- const existing = await storage.getRecord(msg.storeName, msg.record.key);
209
- if (existing && msg.record.version <= existing.version) return;
210
- let resources;
211
- if (msg.storeIndex === 0) {
212
- resources = deepMerge(
213
- _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _11 => _11.resources]), () => ( {})),
214
- msg.record.resources
215
- );
216
- } else {
217
- resources = { ..._nullishCoalesce(_optionalChain([existing, 'optionalAccess', _12 => _12.resources]), () => ( {})), ...msg.record.resources };
218
- }
219
- const mergedRecord = { ...msg.record, resources };
220
- await storage.putRecord(msg.storeName, mergedRecord);
221
- await callbacks.onModuleLoaded({
222
- storeName: msg.task.storeName,
223
- langCode: mergedRecord.langCode,
224
- moduleCode: mergedRecord.moduleCode,
225
- version: mergedRecord.version
226
- });
227
- })().catch(() => {
228
- });
229
- this.pendingCallbacks.add(p);
230
- p.finally(() => this.pendingCallbacks.delete(p));
231
- } else if (msg.type === "moduleError") {
232
- _optionalChain([callbacks, 'access', _13 => _13.onModuleError, 'optionalCall', _14 => _14(msg)]);
233
- } else if (msg.type === "done" || msg.type === "error") {
234
- if (msg.type === "error") _optionalChain([callbacks, 'access', _15 => _15.onError, 'optionalCall', _16 => _16()]);
235
- this.finalize(callbacks);
236
- }
237
- });
238
- worker.postMessage({ type: "start", payload });
239
- }
240
- terminate() {
241
- _optionalChain([this, 'access', _17 => _17.worker, 'optionalAccess', _18 => _18.terminate, 'call', _19 => _19()]);
242
- this.worker = null;
243
- }
244
- isRunning() {
245
- return this.worker !== null;
246
- }
247
- finalize(callbacks) {
248
- if (this.finalized) return;
249
- this.finalized = true;
250
- const pending = [...this.pendingCallbacks];
251
- Promise.allSettled(pending).then(() => {
252
- this.terminate();
253
- callbacks.onDone();
254
- });
255
- }
256
- };
257
-
258
227
  // src/core/manager.ts
259
- var DB_NAME = "i18n_cache";
260
228
  var PRIORITY_MODULES = ["ENUMS", "CUSTOMER"];
261
229
  var currentLang = "zh_CN";
262
230
  var currentSig = null;
@@ -345,7 +313,7 @@ async function getResource(moduleCode, langCode) {
345
313
  const result = results[i];
346
314
  if (result.status === "rejected") continue;
347
315
  const record = result.value;
348
- if (!_optionalChain([record, 'optionalAccess', _20 => _20.resources])) continue;
316
+ if (!_optionalChain([record, 'optionalAccess', _18 => _18.resources])) continue;
349
317
  merged = i === 0 ? deepMerge(merged, record.resources) : deepMerge(merged, flatToNested(record.resources));
350
318
  }
351
319
  return merged;
@@ -400,7 +368,7 @@ async function checkCacheVersion(storage, options) {
400
368
  const baseStoreName = resolvedStores[0].name;
401
369
  const current = String(options.version);
402
370
  const record = await storage.getRecord(baseStoreName, CACHE_VERSION_KEY).catch(() => void 0);
403
- const stored = _optionalChain([record, 'optionalAccess', _21 => _21.resources, 'optionalAccess', _22 => _22["value"]]);
371
+ const stored = _optionalChain([record, 'optionalAccess', _19 => _19.resources, 'optionalAccess', _20 => _20["value"]]);
404
372
  if (stored === current) return;
405
373
  for (const store of options.stores) {
406
374
  await storage.clearStore(store.name);
@@ -432,7 +400,7 @@ async function doUnloginPull(storage, options) {
432
400
  const existing = await storage.getRecord(baseStore.name, key);
433
401
  const parsed = parseI18nValues(_nullishCoalesce(mod.i18nValues, () => ( [])));
434
402
  const resources = deepMerge(
435
- _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _23 => _23.resources]), () => ( {})),
403
+ _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _21 => _21.resources]), () => ( {})),
436
404
  flatToNested(parsed)
437
405
  );
438
406
  await storage.putRecord(baseStore.name, {
@@ -469,7 +437,7 @@ async function startWorkerFull(options) {
469
437
  function runWorker(options, tasks, pull) {
470
438
  return new Promise((resolve, reject) => {
471
439
  const { apiContext } = options;
472
- const workerWritesDB = _nullishCoalesce(managerOptions.workerWritesDB, () => ( false));
440
+ const storage = managerOptions.storage;
473
441
  workerManager.start(
474
442
  managerOptions.createWorker,
475
443
  {
@@ -477,20 +445,45 @@ function runWorker(options, tasks, pull) {
477
445
  headers: apiContext.getHeaders(),
478
446
  pullPath: pull.path,
479
447
  pullMethod: _nullishCoalesce(pull.method, () => ( "GET")),
480
- stores: resolvedStores,
481
- tasks,
482
- dbName: DB_NAME
448
+ tasks
483
449
  },
484
450
  {
485
- onModuleLoaded: async (data) => {
486
- await onModuleLoaded(data);
451
+ onRawData: async (task, raw) => {
452
+ const blocks = pull.transform ? pull.transform(raw) : raw;
453
+ const store = resolvedStores.find((s) => s.name === task.storeName);
454
+ if (!store) return;
455
+ const storeIndex = resolvedStores.indexOf(store);
456
+ for (const block of blocks) {
457
+ for (const mod of _nullishCoalesce(block.modules, () => ( []))) {
458
+ const key = buildKey(mod.moduleCode, block.langCode, store);
459
+ const existing = await storage.getRecord(store.name, key);
460
+ if (existing && mod.version <= existing.version) continue;
461
+ const parsed = parseI18nValues(_nullishCoalesce(mod.i18nValues, () => ( [])));
462
+ const resources = storeIndex === 0 ? deepMerge(
463
+ _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _22 => _22.resources]), () => ( {})),
464
+ flatToNested(parsed)
465
+ ) : { ..._nullishCoalesce(_optionalChain([existing, 'optionalAccess', _23 => _23.resources]), () => ( {})), ...parsed };
466
+ await storage.putRecord(store.name, {
467
+ key,
468
+ moduleCode: mod.moduleCode,
469
+ langCode: block.langCode,
470
+ version: mod.version,
471
+ resources
472
+ });
473
+ await onModuleLoaded({
474
+ storeName: task.storeName,
475
+ langCode: block.langCode,
476
+ moduleCode: mod.moduleCode,
477
+ version: mod.version
478
+ });
479
+ }
480
+ }
487
481
  },
488
482
  onModuleError: (_data) => {
489
483
  },
490
484
  onDone: resolve,
491
485
  onError: () => reject(new Error("[i18n] Worker fatal error"))
492
- },
493
- workerWritesDB ? void 0 : managerOptions.storage
486
+ }
494
487
  );
495
488
  });
496
489
  }
@@ -119,6 +119,56 @@ var SSEClient = class {
119
119
  }
120
120
  };
121
121
 
122
+ // src/core/worker-manager.ts
123
+ var WorkerManager = class {
124
+ constructor() {
125
+ this.worker = null;
126
+ this.pendingCallbacks = /* @__PURE__ */ new Set();
127
+ this.finalized = false;
128
+ }
129
+ start(createWorker, payload, callbacks) {
130
+ this.terminate();
131
+ this.finalized = false;
132
+ this.pendingCallbacks = /* @__PURE__ */ new Set();
133
+ if (payload.tasks.length === 0) {
134
+ callbacks.onDone();
135
+ return;
136
+ }
137
+ const worker = createWorker();
138
+ this.worker = worker;
139
+ worker.onMessage((msg) => {
140
+ if (msg.type === "rawData") {
141
+ const p = callbacks.onRawData(msg.task, msg.raw).catch(() => {
142
+ });
143
+ this.pendingCallbacks.add(p);
144
+ p.finally(() => this.pendingCallbacks.delete(p));
145
+ } else if (msg.type === "moduleError") {
146
+ callbacks.onModuleError?.(msg);
147
+ } else if (msg.type === "done" || msg.type === "error") {
148
+ if (msg.type === "error") callbacks.onError?.();
149
+ this.finalize(callbacks);
150
+ }
151
+ });
152
+ worker.postMessage({ type: "start", payload });
153
+ }
154
+ terminate() {
155
+ this.worker?.terminate();
156
+ this.worker = null;
157
+ }
158
+ isRunning() {
159
+ return this.worker !== null;
160
+ }
161
+ finalize(callbacks) {
162
+ if (this.finalized) return;
163
+ this.finalized = true;
164
+ const pending = [...this.pendingCallbacks];
165
+ Promise.allSettled(pending).then(() => {
166
+ this.terminate();
167
+ callbacks.onDone();
168
+ });
169
+ }
170
+ };
171
+
122
172
  // src/core/utils.ts
123
173
  function buildKey(moduleCode, langCode, store) {
124
174
  return store.cacheGroupKey ? `${moduleCode}_${langCode}_${store.cacheGroupKey}` : `${moduleCode}_${langCode}`;
@@ -174,89 +224,7 @@ function toQueryString(params) {
174
224
  ).toString();
175
225
  }
176
226
 
177
- // src/core/worker-manager.ts
178
- var WorkerManager = class {
179
- constructor() {
180
- this.worker = null;
181
- this.pendingCallbacks = /* @__PURE__ */ new Set();
182
- this.finalized = false;
183
- }
184
- start(createWorker, payload, callbacks, storage) {
185
- this.terminate();
186
- this.finalized = false;
187
- this.pendingCallbacks = /* @__PURE__ */ new Set();
188
- if (payload.tasks.length === 0) {
189
- callbacks.onDone();
190
- return;
191
- }
192
- const worker = createWorker();
193
- this.worker = worker;
194
- worker.onMessage((msg) => {
195
- if (msg.type === "moduleLoaded") {
196
- const m = msg;
197
- const p = callbacks.onModuleLoaded({
198
- storeName: m.storeName,
199
- langCode: m.langCode,
200
- moduleCode: m.moduleCode,
201
- version: m.version
202
- });
203
- this.pendingCallbacks.add(p);
204
- p.finally(() => this.pendingCallbacks.delete(p));
205
- } else if (msg.type === "dataReady") {
206
- if (!storage) return;
207
- const p = (async () => {
208
- const existing = await storage.getRecord(msg.storeName, msg.record.key);
209
- if (existing && msg.record.version <= existing.version) return;
210
- let resources;
211
- if (msg.storeIndex === 0) {
212
- resources = deepMerge(
213
- existing?.resources ?? {},
214
- msg.record.resources
215
- );
216
- } else {
217
- resources = { ...existing?.resources ?? {}, ...msg.record.resources };
218
- }
219
- const mergedRecord = { ...msg.record, resources };
220
- await storage.putRecord(msg.storeName, mergedRecord);
221
- await callbacks.onModuleLoaded({
222
- storeName: msg.task.storeName,
223
- langCode: mergedRecord.langCode,
224
- moduleCode: mergedRecord.moduleCode,
225
- version: mergedRecord.version
226
- });
227
- })().catch(() => {
228
- });
229
- this.pendingCallbacks.add(p);
230
- p.finally(() => this.pendingCallbacks.delete(p));
231
- } else if (msg.type === "moduleError") {
232
- callbacks.onModuleError?.(msg);
233
- } else if (msg.type === "done" || msg.type === "error") {
234
- if (msg.type === "error") callbacks.onError?.();
235
- this.finalize(callbacks);
236
- }
237
- });
238
- worker.postMessage({ type: "start", payload });
239
- }
240
- terminate() {
241
- this.worker?.terminate();
242
- this.worker = null;
243
- }
244
- isRunning() {
245
- return this.worker !== null;
246
- }
247
- finalize(callbacks) {
248
- if (this.finalized) return;
249
- this.finalized = true;
250
- const pending = [...this.pendingCallbacks];
251
- Promise.allSettled(pending).then(() => {
252
- this.terminate();
253
- callbacks.onDone();
254
- });
255
- }
256
- };
257
-
258
227
  // src/core/manager.ts
259
- var DB_NAME = "i18n_cache";
260
228
  var PRIORITY_MODULES = ["ENUMS", "CUSTOMER"];
261
229
  var currentLang = "zh_CN";
262
230
  var currentSig = null;
@@ -469,7 +437,7 @@ async function startWorkerFull(options) {
469
437
  function runWorker(options, tasks, pull) {
470
438
  return new Promise((resolve, reject) => {
471
439
  const { apiContext } = options;
472
- const workerWritesDB = managerOptions.workerWritesDB ?? false;
440
+ const storage = managerOptions.storage;
473
441
  workerManager.start(
474
442
  managerOptions.createWorker,
475
443
  {
@@ -477,20 +445,45 @@ function runWorker(options, tasks, pull) {
477
445
  headers: apiContext.getHeaders(),
478
446
  pullPath: pull.path,
479
447
  pullMethod: pull.method ?? "GET",
480
- stores: resolvedStores,
481
- tasks,
482
- dbName: DB_NAME
448
+ tasks
483
449
  },
484
450
  {
485
- onModuleLoaded: async (data) => {
486
- await onModuleLoaded(data);
451
+ onRawData: async (task, raw) => {
452
+ const blocks = pull.transform ? pull.transform(raw) : raw;
453
+ const store = resolvedStores.find((s) => s.name === task.storeName);
454
+ if (!store) return;
455
+ const storeIndex = resolvedStores.indexOf(store);
456
+ for (const block of blocks) {
457
+ for (const mod of block.modules ?? []) {
458
+ const key = buildKey(mod.moduleCode, block.langCode, store);
459
+ const existing = await storage.getRecord(store.name, key);
460
+ if (existing && mod.version <= existing.version) continue;
461
+ const parsed = parseI18nValues(mod.i18nValues ?? []);
462
+ const resources = storeIndex === 0 ? deepMerge(
463
+ existing?.resources ?? {},
464
+ flatToNested(parsed)
465
+ ) : { ...existing?.resources ?? {}, ...parsed };
466
+ await storage.putRecord(store.name, {
467
+ key,
468
+ moduleCode: mod.moduleCode,
469
+ langCode: block.langCode,
470
+ version: mod.version,
471
+ resources
472
+ });
473
+ await onModuleLoaded({
474
+ storeName: task.storeName,
475
+ langCode: block.langCode,
476
+ moduleCode: mod.moduleCode,
477
+ version: mod.version
478
+ });
479
+ }
480
+ }
487
481
  },
488
482
  onModuleError: (_data) => {
489
483
  },
490
484
  onDone: resolve,
491
485
  onError: () => reject(new Error("[i18n] Worker fatal error"))
492
- },
493
- workerWritesDB ? void 0 : managerOptions.storage
486
+ }
494
487
  );
495
488
  });
496
489
  }
package/dist/index.cjs CHANGED
@@ -7,7 +7,7 @@ var _chunkAJJKJPNBcjs = require('./chunk-AJJKJPNB.cjs');
7
7
 
8
8
 
9
9
 
10
- var _chunkMQYSUEEWcjs = require('./chunk-MQYSUEEW.cjs');
10
+ var _chunkJPKSBSEOcjs = require('./chunk-JPKSBSEO.cjs');
11
11
 
12
12
  // src/index.ts
13
13
  var _i18next = require('i18next'); var _i18next2 = _interopRequireDefault(_i18next);
@@ -165,9 +165,8 @@ if (!_i18next2.default.isInitialized) {
165
165
  }
166
166
  });
167
167
  }
168
- var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } = _chunkMQYSUEEWcjs.createI18nManager.call(void 0, {
168
+ var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } = _chunkJPKSBSEOcjs.createI18nManager.call(void 0, {
169
169
  storage: new IndexedDBAdapter(),
170
- workerWritesDB: true,
171
170
  createWorker: () => new (0, _chunkAJJKJPNBcjs.WebWorkerAdapter)(
172
171
  new Worker(new URL("./workers/preload-worker.js", import.meta.url), { type: "module" })
173
172
  )
@@ -182,4 +181,4 @@ var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } =
182
181
 
183
182
 
184
183
 
185
- exports.I18N_RESOURCES_UPDATED_EVENT = _chunkMQYSUEEWcjs.I18N_RESOURCES_UPDATED_EVENT; exports.closeSSE = closeSSE; exports.emitI18nResourcesUpdated = _chunkMQYSUEEWcjs.emitI18nResourcesUpdated; exports.ensureModules = ensureModules; exports.getAllRecordsByModule = getAllRecordsByModule; exports.getResource = getResource; exports.initI18n = initI18n; exports.useDict = _chunkAJJKJPNBcjs.useDict; exports.useTranslation = _chunkAJJKJPNBcjs.useTranslation;
184
+ exports.I18N_RESOURCES_UPDATED_EVENT = _chunkJPKSBSEOcjs.I18N_RESOURCES_UPDATED_EVENT; exports.closeSSE = closeSSE; exports.emitI18nResourcesUpdated = _chunkJPKSBSEOcjs.emitI18nResourcesUpdated; exports.ensureModules = ensureModules; exports.getAllRecordsByModule = getAllRecordsByModule; exports.getResource = getResource; exports.initI18n = initI18n; exports.useDict = _chunkAJJKJPNBcjs.useDict; exports.useTranslation = _chunkAJJKJPNBcjs.useTranslation;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from './cacheEvents-5-eLxrSg.cjs';
2
- export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, W as WorkerLike, h as emitI18nResourcesUpdated } from './cacheEvents-5-eLxrSg.cjs';
1
+ import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from './cacheEvents-CSwgzbob.cjs';
2
+ export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, W as WorkerLike, h as emitI18nResourcesUpdated } from './cacheEvents-CSwgzbob.cjs';
3
3
  export { u as useDict } from './hooks-ClO29Chr.cjs';
4
4
  export { useTranslation } from 'react-i18next';
5
5
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from './cacheEvents-5-eLxrSg.js';
2
- export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, W as WorkerLike, h as emitI18nResourcesUpdated } from './cacheEvents-5-eLxrSg.js';
1
+ import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from './cacheEvents-CSwgzbob.js';
2
+ export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, W as WorkerLike, h as emitI18nResourcesUpdated } from './cacheEvents-CSwgzbob.js';
3
3
  export { u as useDict } from './hooks-ClO29Chr.js';
4
4
  export { useTranslation } from 'react-i18next';
5
5
 
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  I18N_RESOURCES_UPDATED_EVENT,
8
8
  createI18nManager,
9
9
  emitI18nResourcesUpdated
10
- } from "./chunk-USTXU3BM.js";
10
+ } from "./chunk-X6D2MZ7M.js";
11
11
 
12
12
  // src/index.ts
13
13
  import i18n from "i18next";
@@ -167,7 +167,6 @@ if (!i18n.isInitialized) {
167
167
  }
168
168
  var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } = createI18nManager({
169
169
  storage: new IndexedDBAdapter(),
170
- workerWritesDB: true,
171
170
  createWorker: () => new WebWorkerAdapter(
172
171
  new Worker(new URL("./workers/preload-worker.js", import.meta.url), { type: "module" })
173
172
  )
package/dist/mp/index.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkMQYSUEEWcjs = require('../chunk-MQYSUEEW.cjs');
5
+ var _chunkJPKSBSEOcjs = require('../chunk-JPKSBSEO.cjs');
6
6
 
7
7
  // src/storage/wx-sqlite.ts
8
8
  var DB_NAME = "i18n_cache";
@@ -181,7 +181,7 @@ function wxFetch(input, init) {
181
181
  }
182
182
 
183
183
  // src/mp/index.ts
184
- var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } = _chunkMQYSUEEWcjs.createI18nManager.call(void 0, {
184
+ var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } = _chunkJPKSBSEOcjs.createI18nManager.call(void 0, {
185
185
  storage: new WxSQLiteAdapter(),
186
186
  createWorker: () => new WxWorkerAdapter(wx.createWorker("workers/preload-worker-mp.js")),
187
187
  fetchFn: wxFetch
@@ -194,4 +194,4 @@ var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } =
194
194
 
195
195
 
196
196
 
197
- exports.I18N_RESOURCES_UPDATED_EVENT = _chunkMQYSUEEWcjs.I18N_RESOURCES_UPDATED_EVENT; exports.closeSSE = closeSSE; exports.emitI18nResourcesUpdated = _chunkMQYSUEEWcjs.emitI18nResourcesUpdated; exports.ensureModules = ensureModules; exports.getAllRecordsByModule = getAllRecordsByModule; exports.getResource = getResource; exports.initI18n = initI18n;
197
+ exports.I18N_RESOURCES_UPDATED_EVENT = _chunkJPKSBSEOcjs.I18N_RESOURCES_UPDATED_EVENT; exports.closeSSE = closeSSE; exports.emitI18nResourcesUpdated = _chunkJPKSBSEOcjs.emitI18nResourcesUpdated; exports.ensureModules = ensureModules; exports.getAllRecordsByModule = getAllRecordsByModule; exports.getResource = getResource; exports.initI18n = initI18n;
@@ -1,5 +1,5 @@
1
- import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-5-eLxrSg.cjs';
2
- export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-5-eLxrSg.cjs';
1
+ import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-CSwgzbob.cjs';
2
+ export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-CSwgzbob.cjs';
3
3
 
4
4
  declare const initI18n: typeof initI18n$1;
5
5
  declare const closeSSE: typeof closeSSE$1;
@@ -1,5 +1,5 @@
1
- import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-5-eLxrSg.js';
2
- export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-5-eLxrSg.js';
1
+ import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-CSwgzbob.js';
2
+ export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-CSwgzbob.js';
3
3
 
4
4
  declare const initI18n: typeof initI18n$1;
5
5
  declare const closeSSE: typeof closeSSE$1;
package/dist/mp/index.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  I18N_RESOURCES_UPDATED_EVENT,
3
3
  createI18nManager,
4
4
  emitI18nResourcesUpdated
5
- } from "../chunk-USTXU3BM.js";
5
+ } from "../chunk-X6D2MZ7M.js";
6
6
 
7
7
  // src/storage/wx-sqlite.ts
8
8
  var DB_NAME = "i18n_cache";
@@ -7,7 +7,7 @@ var _chunkAJJKJPNBcjs = require('../chunk-AJJKJPNB.cjs');
7
7
 
8
8
 
9
9
 
10
- var _chunkMQYSUEEWcjs = require('../chunk-MQYSUEEW.cjs');
10
+ var _chunkJPKSBSEOcjs = require('../chunk-JPKSBSEO.cjs');
11
11
 
12
12
  // src/native/index.ts
13
13
  var _i18next = require('i18next'); var _i18next2 = _interopRequireDefault(_i18next);
@@ -121,7 +121,7 @@ if (!_i18next2.default.isInitialized) {
121
121
  }
122
122
  });
123
123
  }
124
- var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } = _chunkMQYSUEEWcjs.createI18nManager.call(void 0, {
124
+ var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } = _chunkJPKSBSEOcjs.createI18nManager.call(void 0, {
125
125
  storage: new SQLiteAdapter(),
126
126
  // Hermes Worker(RN 0.71+),API 与 Web Worker 一致
127
127
  createWorker: () => new (0, _chunkAJJKJPNBcjs.WebWorkerAdapter)(
@@ -138,4 +138,4 @@ var { initI18n, closeSSE, ensureModules, getResource, getAllRecordsByModule } =
138
138
 
139
139
 
140
140
 
141
- exports.I18N_RESOURCES_UPDATED_EVENT = _chunkMQYSUEEWcjs.I18N_RESOURCES_UPDATED_EVENT; exports.closeSSE = closeSSE; exports.emitI18nResourcesUpdated = _chunkMQYSUEEWcjs.emitI18nResourcesUpdated; exports.ensureModules = ensureModules; exports.getAllRecordsByModule = getAllRecordsByModule; exports.getResource = getResource; exports.initI18n = initI18n; exports.useDict = _chunkAJJKJPNBcjs.useDict; exports.useTranslation = _chunkAJJKJPNBcjs.useTranslation;
141
+ exports.I18N_RESOURCES_UPDATED_EVENT = _chunkJPKSBSEOcjs.I18N_RESOURCES_UPDATED_EVENT; exports.closeSSE = closeSSE; exports.emitI18nResourcesUpdated = _chunkJPKSBSEOcjs.emitI18nResourcesUpdated; exports.ensureModules = ensureModules; exports.getAllRecordsByModule = getAllRecordsByModule; exports.getResource = getResource; exports.initI18n = initI18n; exports.useDict = _chunkAJJKJPNBcjs.useDict; exports.useTranslation = _chunkAJJKJPNBcjs.useTranslation;
@@ -1,5 +1,5 @@
1
- import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-5-eLxrSg.cjs';
2
- export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-5-eLxrSg.cjs';
1
+ import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-CSwgzbob.cjs';
2
+ export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-CSwgzbob.cjs';
3
3
  export { u as useDict } from '../hooks-ClO29Chr.cjs';
4
4
  export { useTranslation } from 'react-i18next';
5
5
 
@@ -1,5 +1,5 @@
1
- import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-5-eLxrSg.js';
2
- export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-5-eLxrSg.js';
1
+ import { c as closeSSE$1, e as ensureModules$1, g as getAllRecordsByModule$1, a as getResource$1, i as initI18n$1 } from '../cacheEvents-CSwgzbob.js';
2
+ export { I as I18N_RESOURCES_UPDATED_EVENT, b as I18nInitOptions, P as PullLangBlock, R as ResourceRecord, S as SSEMessage, d as StandardPullParams, f as StoreConfig, h as emitI18nResourcesUpdated } from '../cacheEvents-CSwgzbob.js';
3
3
  export { u as useDict } from '../hooks-ClO29Chr.js';
4
4
  export { useTranslation } from 'react-i18next';
5
5
 
@@ -7,7 +7,7 @@ import {
7
7
  I18N_RESOURCES_UPDATED_EVENT,
8
8
  createI18nManager,
9
9
  emitI18nResourcesUpdated
10
- } from "../chunk-USTXU3BM.js";
10
+ } from "../chunk-X6D2MZ7M.js";
11
11
 
12
12
  // src/native/index.ts
13
13
  import i18n from "i18next";
@@ -1,40 +1,18 @@
1
1
  "use strict"; function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/workers/preload-worker-rn.ts
2
- function flatToNested(flat) {
3
- const result = {};
4
- for (const [key, value] of Object.entries(flat)) {
5
- const parts = key.split(".");
6
- let cur = result;
7
- for (let i = 0; i < parts.length - 1; i++) {
8
- const part = parts[i];
9
- if (typeof cur[part] !== "object" || cur[part] === null) cur[part] = {};
10
- cur = cur[part];
11
- }
12
- cur[parts[parts.length - 1]] = value;
13
- }
14
- return result;
15
- }
16
- function parseI18nValues(values) {
17
- const result = {};
18
- for (const { termCode, langValue } of values) {
19
- if (termCode && langValue !== void 0) result[termCode] = _nullishCoalesce(langValue, () => ( ""));
20
- }
21
- return result;
22
- }
23
- function buildKey(moduleCode, langCode, store) {
24
- return store.cacheGroupKey ? `${moduleCode}_${langCode}_${store.cacheGroupKey}` : `${moduleCode}_${langCode}`;
25
- }
26
2
  function toQueryString(params) {
27
3
  return new URLSearchParams(
28
4
  Object.entries(params).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])
29
5
  ).toString();
30
6
  }
31
7
  async function processTask(task, payload) {
32
- const { baseURL, headers, pullPath, pullMethod, stores } = payload;
33
- const params = {};
34
- if (task.storeName) params["storeName"] = task.storeName;
35
- if (task.langCode) params["langCode"] = task.langCode;
36
- if (task.moduleCode) params["moduleCode"] = task.moduleCode;
37
- if (task.version != null) params["version"] = String(task.version);
8
+ const { baseURL, headers, pullPath, pullMethod } = payload;
9
+ const params = _nullishCoalesce(task.params, () => ( {}));
10
+ if (!task.params) {
11
+ if (task.storeName) params["storeName"] = task.storeName;
12
+ if (task.langCode) params["langCode"] = task.langCode;
13
+ if (task.moduleCode) params["moduleCode"] = task.moduleCode;
14
+ if (task.version != null) params["version"] = task.version;
15
+ }
38
16
  const url = baseURL + pullPath;
39
17
  let res;
40
18
  if (pullMethod === "POST") {
@@ -44,33 +22,12 @@ async function processTask(task, payload) {
44
22
  body: JSON.stringify(params)
45
23
  });
46
24
  } else {
47
- res = await fetch(`${url}?${toQueryString(params)}`, { headers });
25
+ const qs = toQueryString(params);
26
+ res = await fetch(qs ? `${url}?${qs}` : url, { headers });
48
27
  }
49
28
  if (!res.ok) throw new Error(`[i18n rn-worker] fetch failed: ${res.status}`);
50
- const blocks = await res.json();
51
- for (const block of blocks) {
52
- for (const mod of _nullishCoalesce(block.modules, () => ( []))) {
53
- const store = stores.find((s) => s.name === task.storeName);
54
- if (!store) continue;
55
- const storeIndex = stores.indexOf(store);
56
- const key = buildKey(mod.moduleCode, block.langCode, store);
57
- const parsed = parseI18nValues(_nullishCoalesce(mod.i18nValues, () => ( [])));
58
- const resources = storeIndex === 0 ? flatToNested(parsed) : parsed;
59
- self.postMessage({
60
- type: "dataReady",
61
- storeName: store.name,
62
- storeIndex,
63
- record: {
64
- key,
65
- moduleCode: mod.moduleCode,
66
- langCode: block.langCode,
67
- version: mod.version,
68
- resources
69
- },
70
- task
71
- });
72
- }
73
- }
29
+ const raw = await res.json();
30
+ self.postMessage({ type: "rawData", task, raw });
74
31
  }
75
32
  self.onmessage = async (event) => {
76
33
  if (event.data.type !== "start") return;
@@ -1,40 +1,18 @@
1
1
  // src/workers/preload-worker-rn.ts
2
- function flatToNested(flat) {
3
- const result = {};
4
- for (const [key, value] of Object.entries(flat)) {
5
- const parts = key.split(".");
6
- let cur = result;
7
- for (let i = 0; i < parts.length - 1; i++) {
8
- const part = parts[i];
9
- if (typeof cur[part] !== "object" || cur[part] === null) cur[part] = {};
10
- cur = cur[part];
11
- }
12
- cur[parts[parts.length - 1]] = value;
13
- }
14
- return result;
15
- }
16
- function parseI18nValues(values) {
17
- const result = {};
18
- for (const { termCode, langValue } of values) {
19
- if (termCode && langValue !== void 0) result[termCode] = langValue ?? "";
20
- }
21
- return result;
22
- }
23
- function buildKey(moduleCode, langCode, store) {
24
- return store.cacheGroupKey ? `${moduleCode}_${langCode}_${store.cacheGroupKey}` : `${moduleCode}_${langCode}`;
25
- }
26
2
  function toQueryString(params) {
27
3
  return new URLSearchParams(
28
4
  Object.entries(params).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])
29
5
  ).toString();
30
6
  }
31
7
  async function processTask(task, payload) {
32
- const { baseURL, headers, pullPath, pullMethod, stores } = payload;
33
- const params = {};
34
- if (task.storeName) params["storeName"] = task.storeName;
35
- if (task.langCode) params["langCode"] = task.langCode;
36
- if (task.moduleCode) params["moduleCode"] = task.moduleCode;
37
- if (task.version != null) params["version"] = String(task.version);
8
+ const { baseURL, headers, pullPath, pullMethod } = payload;
9
+ const params = task.params ?? {};
10
+ if (!task.params) {
11
+ if (task.storeName) params["storeName"] = task.storeName;
12
+ if (task.langCode) params["langCode"] = task.langCode;
13
+ if (task.moduleCode) params["moduleCode"] = task.moduleCode;
14
+ if (task.version != null) params["version"] = task.version;
15
+ }
38
16
  const url = baseURL + pullPath;
39
17
  let res;
40
18
  if (pullMethod === "POST") {
@@ -44,33 +22,12 @@ async function processTask(task, payload) {
44
22
  body: JSON.stringify(params)
45
23
  });
46
24
  } else {
47
- res = await fetch(`${url}?${toQueryString(params)}`, { headers });
25
+ const qs = toQueryString(params);
26
+ res = await fetch(qs ? `${url}?${qs}` : url, { headers });
48
27
  }
49
28
  if (!res.ok) throw new Error(`[i18n rn-worker] fetch failed: ${res.status}`);
50
- const blocks = await res.json();
51
- for (const block of blocks) {
52
- for (const mod of block.modules ?? []) {
53
- const store = stores.find((s) => s.name === task.storeName);
54
- if (!store) continue;
55
- const storeIndex = stores.indexOf(store);
56
- const key = buildKey(mod.moduleCode, block.langCode, store);
57
- const parsed = parseI18nValues(mod.i18nValues ?? []);
58
- const resources = storeIndex === 0 ? flatToNested(parsed) : parsed;
59
- self.postMessage({
60
- type: "dataReady",
61
- storeName: store.name,
62
- storeIndex,
63
- record: {
64
- key,
65
- moduleCode: mod.moduleCode,
66
- langCode: block.langCode,
67
- version: mod.version,
68
- resources
69
- },
70
- task
71
- });
72
- }
73
- }
29
+ const raw = await res.json();
30
+ self.postMessage({ type: "rawData", task, raw });
74
31
  }
75
32
  self.onmessage = async (event) => {
76
33
  if (event.data.type !== "start") return;
@@ -1,85 +1,11 @@
1
- "use strict"; function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/workers/preload-worker.ts
2
- function flatToNested(flat) {
3
- const result = {};
4
- for (const [key, value] of Object.entries(flat)) {
5
- const parts = key.split(".");
6
- let cur = result;
7
- for (let i = 0; i < parts.length - 1; i++) {
8
- const part = parts[i];
9
- if (typeof cur[part] !== "object" || cur[part] === null) cur[part] = {};
10
- cur = cur[part];
11
- }
12
- cur[parts[parts.length - 1]] = value;
13
- }
14
- return result;
15
- }
16
- function deepMerge(target, source) {
17
- const result = { ...target };
18
- for (const [key, sv] of Object.entries(source)) {
19
- const tv = result[key];
20
- if (sv !== null && typeof sv === "object" && !Array.isArray(sv) && tv !== null && typeof tv === "object" && !Array.isArray(tv)) {
21
- result[key] = deepMerge(tv, sv);
22
- } else {
23
- result[key] = sv;
24
- }
25
- }
26
- return result;
27
- }
28
- function parseI18nValues(values) {
29
- const result = {};
30
- for (const { termCode, langValue } of values) {
31
- if (termCode && langValue !== void 0) result[termCode] = _nullishCoalesce(langValue, () => ( ""));
32
- }
33
- return result;
34
- }
35
- function buildKey(moduleCode, langCode, store) {
36
- return store.cacheGroupKey ? `${moduleCode}_${langCode}_${store.cacheGroupKey}` : `${moduleCode}_${langCode}`;
37
- }
1
+ "use strict"; function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/workers/preload-worker.ts
38
2
  function toQueryString(params) {
39
3
  return new URLSearchParams(
40
4
  Object.entries(params).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])
41
5
  ).toString();
42
6
  }
43
- var db = null;
44
- function openDB(dbName, storeNames) {
45
- return new Promise((resolve, reject) => {
46
- const req = indexedDB.open(dbName, 2);
47
- req.onupgradeneeded = (event) => {
48
- const database = event.target.result;
49
- for (const name of storeNames) {
50
- const storeName = `i18n_resources_${name}`;
51
- if (!database.objectStoreNames.contains(storeName)) {
52
- const s = database.createObjectStore(storeName, { keyPath: "key" });
53
- s.createIndex("by_module", "moduleCode");
54
- s.createIndex("by_language", "langCode");
55
- }
56
- }
57
- if (!database.objectStoreNames.contains("i18n_meta")) {
58
- database.createObjectStore("i18n_meta", { keyPath: "key" });
59
- }
60
- };
61
- req.onsuccess = () => resolve(req.result);
62
- req.onerror = () => reject(req.error);
63
- });
64
- }
65
- function idbGet(database, storeName, key) {
66
- return new Promise((resolve, reject) => {
67
- const tx = database.transaction(storeName, "readonly");
68
- const req = tx.objectStore(storeName).get(key);
69
- req.onsuccess = () => resolve(req.result);
70
- req.onerror = () => reject(req.error);
71
- });
72
- }
73
- function idbPut(database, storeName, value) {
74
- return new Promise((resolve, reject) => {
75
- const tx = database.transaction(storeName, "readwrite");
76
- const req = tx.objectStore(storeName).put(value);
77
- req.onsuccess = () => resolve();
78
- req.onerror = () => reject(req.error);
79
- });
80
- }
81
7
  async function processTask(task, payload) {
82
- const { baseURL, headers, pullPath, pullMethod, stores } = payload;
8
+ const { baseURL, headers, pullPath, pullMethod } = payload;
83
9
  const params = _nullishCoalesce(task.params, () => ( {}));
84
10
  if (!task.params) {
85
11
  if (task.storeName) params["storeName"] = task.storeName;
@@ -100,62 +26,12 @@ async function processTask(task, payload) {
100
26
  res = await fetch(qs ? `${url}?${qs}` : url, { headers });
101
27
  }
102
28
  if (!res.ok) throw new Error(`[i18n worker] fetch failed: ${res.status}`);
103
- const blocks = await res.json();
104
- for (const block of blocks) {
105
- for (const mod of _nullishCoalesce(block.modules, () => ( []))) {
106
- const store = stores.find((s) => s.name === task.storeName);
107
- if (!store) continue;
108
- const storeIndex = stores.indexOf(store);
109
- const idbStoreName = `i18n_resources_${store.name}`;
110
- const key = buildKey(mod.moduleCode, block.langCode, store);
111
- const parsed = parseI18nValues(_nullishCoalesce(mod.i18nValues, () => ( [])));
112
- let resources;
113
- if (storeIndex === 0) {
114
- const existing = await idbGet(
115
- db,
116
- idbStoreName,
117
- key
118
- );
119
- resources = deepMerge(
120
- _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _ => _.resources]), () => ( {})),
121
- flatToNested(parsed)
122
- );
123
- } else {
124
- const existing = await idbGet(
125
- db,
126
- idbStoreName,
127
- key
128
- );
129
- resources = { ..._nullishCoalesce(_optionalChain([existing, 'optionalAccess', _2 => _2.resources]), () => ( {})), ...parsed };
130
- }
131
- const record = {
132
- key,
133
- moduleCode: mod.moduleCode,
134
- langCode: block.langCode,
135
- version: mod.version,
136
- resources
137
- };
138
- await idbPut(db, idbStoreName, record);
139
- self.postMessage({
140
- type: "moduleLoaded",
141
- storeName: task.storeName,
142
- langCode: block.langCode,
143
- moduleCode: mod.moduleCode,
144
- version: mod.version
145
- });
146
- }
147
- }
29
+ const raw = await res.json();
30
+ self.postMessage({ type: "rawData", task, raw });
148
31
  }
149
32
  self.onmessage = async (event) => {
150
33
  if (event.data.type !== "start") return;
151
34
  const { payload } = event.data;
152
- const storeNames = payload.stores.map((s) => s.name);
153
- try {
154
- db = await openDB(payload.dbName, storeNames);
155
- } catch (err) {
156
- self.postMessage({ type: "error", message: String(err) });
157
- return;
158
- }
159
35
  for (const task of payload.tasks) {
160
36
  try {
161
37
  await processTask(task, payload);
@@ -1,85 +1,11 @@
1
1
  // src/workers/preload-worker.ts
2
- function flatToNested(flat) {
3
- const result = {};
4
- for (const [key, value] of Object.entries(flat)) {
5
- const parts = key.split(".");
6
- let cur = result;
7
- for (let i = 0; i < parts.length - 1; i++) {
8
- const part = parts[i];
9
- if (typeof cur[part] !== "object" || cur[part] === null) cur[part] = {};
10
- cur = cur[part];
11
- }
12
- cur[parts[parts.length - 1]] = value;
13
- }
14
- return result;
15
- }
16
- function deepMerge(target, source) {
17
- const result = { ...target };
18
- for (const [key, sv] of Object.entries(source)) {
19
- const tv = result[key];
20
- if (sv !== null && typeof sv === "object" && !Array.isArray(sv) && tv !== null && typeof tv === "object" && !Array.isArray(tv)) {
21
- result[key] = deepMerge(tv, sv);
22
- } else {
23
- result[key] = sv;
24
- }
25
- }
26
- return result;
27
- }
28
- function parseI18nValues(values) {
29
- const result = {};
30
- for (const { termCode, langValue } of values) {
31
- if (termCode && langValue !== void 0) result[termCode] = langValue ?? "";
32
- }
33
- return result;
34
- }
35
- function buildKey(moduleCode, langCode, store) {
36
- return store.cacheGroupKey ? `${moduleCode}_${langCode}_${store.cacheGroupKey}` : `${moduleCode}_${langCode}`;
37
- }
38
2
  function toQueryString(params) {
39
3
  return new URLSearchParams(
40
4
  Object.entries(params).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])
41
5
  ).toString();
42
6
  }
43
- var db = null;
44
- function openDB(dbName, storeNames) {
45
- return new Promise((resolve, reject) => {
46
- const req = indexedDB.open(dbName, 2);
47
- req.onupgradeneeded = (event) => {
48
- const database = event.target.result;
49
- for (const name of storeNames) {
50
- const storeName = `i18n_resources_${name}`;
51
- if (!database.objectStoreNames.contains(storeName)) {
52
- const s = database.createObjectStore(storeName, { keyPath: "key" });
53
- s.createIndex("by_module", "moduleCode");
54
- s.createIndex("by_language", "langCode");
55
- }
56
- }
57
- if (!database.objectStoreNames.contains("i18n_meta")) {
58
- database.createObjectStore("i18n_meta", { keyPath: "key" });
59
- }
60
- };
61
- req.onsuccess = () => resolve(req.result);
62
- req.onerror = () => reject(req.error);
63
- });
64
- }
65
- function idbGet(database, storeName, key) {
66
- return new Promise((resolve, reject) => {
67
- const tx = database.transaction(storeName, "readonly");
68
- const req = tx.objectStore(storeName).get(key);
69
- req.onsuccess = () => resolve(req.result);
70
- req.onerror = () => reject(req.error);
71
- });
72
- }
73
- function idbPut(database, storeName, value) {
74
- return new Promise((resolve, reject) => {
75
- const tx = database.transaction(storeName, "readwrite");
76
- const req = tx.objectStore(storeName).put(value);
77
- req.onsuccess = () => resolve();
78
- req.onerror = () => reject(req.error);
79
- });
80
- }
81
7
  async function processTask(task, payload) {
82
- const { baseURL, headers, pullPath, pullMethod, stores } = payload;
8
+ const { baseURL, headers, pullPath, pullMethod } = payload;
83
9
  const params = task.params ?? {};
84
10
  if (!task.params) {
85
11
  if (task.storeName) params["storeName"] = task.storeName;
@@ -100,62 +26,12 @@ async function processTask(task, payload) {
100
26
  res = await fetch(qs ? `${url}?${qs}` : url, { headers });
101
27
  }
102
28
  if (!res.ok) throw new Error(`[i18n worker] fetch failed: ${res.status}`);
103
- const blocks = await res.json();
104
- for (const block of blocks) {
105
- for (const mod of block.modules ?? []) {
106
- const store = stores.find((s) => s.name === task.storeName);
107
- if (!store) continue;
108
- const storeIndex = stores.indexOf(store);
109
- const idbStoreName = `i18n_resources_${store.name}`;
110
- const key = buildKey(mod.moduleCode, block.langCode, store);
111
- const parsed = parseI18nValues(mod.i18nValues ?? []);
112
- let resources;
113
- if (storeIndex === 0) {
114
- const existing = await idbGet(
115
- db,
116
- idbStoreName,
117
- key
118
- );
119
- resources = deepMerge(
120
- existing?.resources ?? {},
121
- flatToNested(parsed)
122
- );
123
- } else {
124
- const existing = await idbGet(
125
- db,
126
- idbStoreName,
127
- key
128
- );
129
- resources = { ...existing?.resources ?? {}, ...parsed };
130
- }
131
- const record = {
132
- key,
133
- moduleCode: mod.moduleCode,
134
- langCode: block.langCode,
135
- version: mod.version,
136
- resources
137
- };
138
- await idbPut(db, idbStoreName, record);
139
- self.postMessage({
140
- type: "moduleLoaded",
141
- storeName: task.storeName,
142
- langCode: block.langCode,
143
- moduleCode: mod.moduleCode,
144
- version: mod.version
145
- });
146
- }
147
- }
29
+ const raw = await res.json();
30
+ self.postMessage({ type: "rawData", task, raw });
148
31
  }
149
32
  self.onmessage = async (event) => {
150
33
  if (event.data.type !== "start") return;
151
34
  const { payload } = event.data;
152
- const storeNames = payload.stores.map((s) => s.name);
153
- try {
154
- db = await openDB(payload.dbName, storeNames);
155
- } catch (err) {
156
- self.postMessage({ type: "error", message: String(err) });
157
- return;
158
- }
159
35
  for (const task of payload.tasks) {
160
36
  try {
161
37
  await processTask(task, payload);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shuo-li/i18n",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "Cross-platform i18n library for Web, React Native and WeChat MiniProgram",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",