@rdlabo/ionic-angular-kit 21.5.17 → 21.5.18

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/README.md CHANGED
@@ -391,11 +391,13 @@ A fleet-canonical HTTP interceptor with:
391
391
 
392
392
  The optional `offline` entry point provides a user/partition-scoped local replica, durable outbox, authenticated
393
393
  session boundary, cursor-based delta pull, aggregate-ordered replay, optimistic updates, retry classification, and a
394
- read-only request-policy interceptor. Synchronized applications provide URL/DTO read policies, a replica puller, and
395
- a command executor through `provideOffline(...)`. External-source or HTTP read caches use
394
+ request-policy interceptor. Synchronized applications provide URL/DTO read policies, optional local-first mutation
395
+ policies, a replica puller, and a command executor through `provideOffline(...)`. External-source or HTTP read caches use
396
396
  `mode: 'readCacheOnly'`; the kit then supplies the empty pull/executor boundary instead of making every product
397
397
  declare dummy adapters.
398
- Mutations are queued explicitly with `OfflineSyncService.enqueue`, not through HTTP interceptor policy.
398
+ Mutations may still call `OfflineSyncService.enqueue` explicitly. A product that must keep ordinary HTTP services
399
+ offline-unaware can instead register `mutationPolicies`; a matched `POST` / `PUT` / `PATCH` / `DELETE` is prepared
400
+ locally before transport and returns an optimistic response while the Outbox owns remote replay.
399
401
  Web storage uses Ionic Storage; iOS and Android use encrypted `@capacitor-community/sqlite`. Importing either the
400
402
  primary entry point or `/offline` does not pull the optional native SQLite plugin into web-only applications.
401
403
 
@@ -447,8 +449,51 @@ returned.
447
449
 
448
450
  The offline interceptor observes real transport responses to update API reachability. For matched `GET`
449
451
  requests only, a transport failure with `status=0` may return a local replica response tagged
450
- `X-Offline-Response: local`. `POST` and other write methods always go to transport unchanged; outbox replay
451
- requests bypass policy with `OFFLINE_BYPASS` while still using the same transport observation.
452
+ `X-Offline-Response: local`. A read policy's optional `projectResponse(response, source)` hook receives both remote
453
+ and local results, so the remote branch can persist first and both branches can return a body from one composer.
454
+ Matched mutation policies return `X-Offline-Response: optimistic` without starting transport. Unmatched writes go to
455
+ transport unchanged. Outbox replay requests bypass policy with `OFFLINE_BYPASS` while still using the same auth
456
+ interceptor and transport observation. Mutation policy matchers must be mutually exclusive: zero matches use normal
457
+ transport, exactly one match runs its `prepare()`, and multiple matches throw `OfflineMutationPolicyConflictError`
458
+ before either `prepare()` or transport starts. This fail-fast boundary prevents provider registration order from
459
+ silently selecting the wrong replica/outbox mutation.
460
+
461
+ ```ts
462
+ @Injectable()
463
+ class ItemReadPolicy implements OfflineRequestPolicy {
464
+ resolve(request: HttpRequest<unknown>): OfflineRequestPlan | null {
465
+ if (request.method !== 'GET' || !request.url.endsWith('/items')) return null;
466
+ return {
467
+ kind: 'read',
468
+ readLocal: () => this.items.readResponse(),
469
+ projectResponse: async (response, source) => {
470
+ if (source === 'remote') await this.items.persist(response.body);
471
+ return response.clone({ body: await this.items.compose() });
472
+ },
473
+ };
474
+ }
475
+ }
476
+
477
+ @Injectable()
478
+ class ItemMutationPolicy implements OfflineMutationRequestPolicy {
479
+ resolve(request: HttpRequest<unknown>): OfflineMutationRequestPlan | null {
480
+ if (request.method !== 'POST' || !request.url.endsWith('/items')) return null;
481
+ return {
482
+ kind: 'mutation',
483
+ prepare: async () => {
484
+ const optimistic = await this.items.enqueueCreate(request.body);
485
+ return new HttpResponse({ status: 202, body: optimistic });
486
+ },
487
+ };
488
+ }
489
+ }
490
+
491
+ provideOffline({
492
+ // repository/schema/executor/puller options omitted
493
+ requestPolicies: [ItemReadPolicy],
494
+ mutationPolicies: [ItemMutationPolicy],
495
+ });
496
+ ```
452
497
 
453
498
  The native offline runtime uses `@capacitor-community/sqlite` on iOS and Android. Install the plugin in the app and
454
499
  sync native projects:
@@ -7,7 +7,7 @@ import { App } from '@capacitor/app';
7
7
  import { Network } from '@capacitor/network';
8
8
  import { HttpErrorResponse, HttpContextToken, HttpResponse } from '@angular/common/http';
9
9
  import { Capacitor } from '@capacitor/core';
10
- import { defer, catchError, throwError, tap, from, concatMap, of } from 'rxjs';
10
+ import { defer, catchError, throwError, concatMap, from, map as map$1, of, tap } from 'rxjs';
11
11
 
12
12
  const MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;
13
13
  const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
@@ -3384,16 +3384,22 @@ function parseOfflineMutationEnvelope(input, options) {
3384
3384
 
3385
3385
  /** outbox再送時にoffline interceptorだけを迂回する。認証・retryは維持する。 */
3386
3386
  const OFFLINE_BYPASS = new HttpContextToken(() => false);
3387
- /** Header attached to responses served from the local replica fallback. */
3387
+ /** Header attached to synthetic local or optimistic responses. */
3388
3388
  const OFFLINE_RESPONSE_HEADER = 'X-Offline-Response';
3389
3389
  /** Multi-provider token containing product request policies. */
3390
3390
  const OFFLINE_REQUEST_POLICIES = new InjectionToken('OFFLINE_REQUEST_POLICIES', {
3391
3391
  factory: () => [],
3392
3392
  });
3393
+ /** Multi-provider token containing product mutation policies. */
3394
+ const OFFLINE_MUTATION_REQUEST_POLICIES = new InjectionToken('OFFLINE_MUTATION_REQUEST_POLICIES', { factory: () => [] });
3393
3395
  /** Registers one product request policy with the offline interceptor. */
3394
3396
  function provideOfflineRequestPolicy(policy) {
3395
3397
  return [policy, { provide: OFFLINE_REQUEST_POLICIES, useExisting: policy, multi: true }];
3396
3398
  }
3399
+ /** Registers one product mutation policy with the offline interceptor. */
3400
+ function provideOfflineMutationRequestPolicy(policy) {
3401
+ return [policy, { provide: OFFLINE_MUTATION_REQUEST_POLICIES, useExisting: policy, multi: true }];
3402
+ }
3397
3403
  /** Resolves the first product policy matching an HTTP request. */
3398
3404
  class OfflineRequestPolicyRegistry {
3399
3405
  #policies = inject(OFFLINE_REQUEST_POLICIES);
@@ -3412,6 +3418,37 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
3412
3418
  type: Injectable,
3413
3419
  args: [{ providedIn: 'root' }]
3414
3420
  }] });
3421
+ /** Raised when more than one mutation policy claims the same request. */
3422
+ class OfflineMutationPolicyConflictError extends Error {
3423
+ constructor(request, matchCount) {
3424
+ super(`${matchCount} offline mutation policies matched ${request.method} ${request.urlWithParams}`);
3425
+ this.name = 'OfflineMutationPolicyConflictError';
3426
+ }
3427
+ }
3428
+ /** Resolves the only product mutation policy matching a write request. */
3429
+ class OfflineMutationRequestPolicyRegistry {
3430
+ #policies = inject(OFFLINE_MUTATION_REQUEST_POLICIES);
3431
+ resolve(request) {
3432
+ let matched = null;
3433
+ let matchCount = 0;
3434
+ for (const policy of this.#policies) {
3435
+ const plan = policy.resolve(request);
3436
+ if (!plan)
3437
+ continue;
3438
+ matched = plan;
3439
+ matchCount += 1;
3440
+ }
3441
+ if (matchCount > 1)
3442
+ throw new OfflineMutationPolicyConflictError(request, matchCount);
3443
+ return matched;
3444
+ }
3445
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationRequestPolicyRegistry, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
3446
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationRequestPolicyRegistry, providedIn: 'root' }); }
3447
+ }
3448
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationRequestPolicyRegistry, decorators: [{
3449
+ type: Injectable,
3450
+ args: [{ providedIn: 'root' }]
3451
+ }] });
3415
3452
 
3416
3453
  /** DI token for the native community SQLite driver. */
3417
3454
  const COMMUNITY_SQLITE = new InjectionToken('COMMUNITY_SQLITE', {
@@ -4239,26 +4276,41 @@ function provideOffline(options) {
4239
4276
  : { provide: OFFLINE_REPLICA_PULLER, useValue: READ_CACHE_ONLY_REPLICA_PULLER },
4240
4277
  ...(options.commandHooks ? [options.commandHooks, { provide: OFFLINE_COMMAND_HOOKS, useExisting: options.commandHooks }] : []),
4241
4278
  ...options.requestPolicies.flatMap((policy) => provideOfflineRequestPolicy(policy)),
4279
+ ...(options.mutationPolicies ?? []).flatMap((policy) => provideOfflineMutationRequestPolicy(policy)),
4242
4280
  ...(options.providers ?? []),
4243
4281
  provideAppInitializer(() => inject(OfflineCoordinatorService).initialize()),
4244
4282
  ]);
4245
4283
  }
4246
4284
 
4247
- /** Applies product offline read policies while observing real API reachability. */
4285
+ const LOCAL_FIRST_MUTATION_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
4286
+ /** Applies product read and local-first mutation policies while observing real API reachability. */
4248
4287
  const offlineInterceptor = (request, next) => {
4249
4288
  const network = inject(OfflineNetworkService);
4250
4289
  const transport = () => observeTransport(next(request), network);
4251
4290
  if (request.context.get(OFFLINE_BYPASS))
4252
4291
  return transport();
4253
- if (request.method !== 'GET')
4254
- return transport();
4255
- const registry = inject(OfflineRequestPolicyRegistry);
4256
- const fallback = inject(OfflineRequestFallbackService);
4257
- const plan = registry.resolve(request);
4258
- if (!plan)
4259
- return transport();
4260
- return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)));
4292
+ if (request.method === 'GET') {
4293
+ const registry = inject(OfflineRequestPolicyRegistry);
4294
+ const fallback = inject(OfflineRequestFallbackService);
4295
+ const plan = registry.resolve(request);
4296
+ if (!plan)
4297
+ return transport();
4298
+ return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectRemoteResponse(event, plan)));
4299
+ }
4300
+ if (LOCAL_FIRST_MUTATION_METHODS.has(request.method)) {
4301
+ const plan = inject(OfflineMutationRequestPolicyRegistry).resolve(request);
4302
+ if (plan) {
4303
+ return defer(() => from(plan.prepare())).pipe(map$1((response) => response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'optimistic') })));
4304
+ }
4305
+ }
4306
+ return transport();
4261
4307
  };
4308
+ function projectRemoteResponse(event, plan) {
4309
+ if (!(event instanceof HttpResponse) || !plan.projectResponse)
4310
+ return of(event);
4311
+ const source = event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';
4312
+ return from(plan.projectResponse(event, source)).pipe(map$1((response) => source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response));
4313
+ }
4262
4314
  function observeTransport(source, network) {
4263
4315
  return source.pipe(tap({
4264
4316
  next: (event) => {
@@ -4305,5 +4357,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
4305
4357
  * Generated bundle index. Do not edit.
4306
4358
  */
4307
4359
 
4308
- export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineMutationProtocolError, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, text };
4360
+ export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, text };
4309
4361
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map