Repository navigation
Expand file tree
/
Copy pathengine.ts
More file actions
6756 lines (6355 loc) · 361 KB
/
Copy pathengine.ts
File metadata and controls
6756 lines (6355 loc) · 361 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { AsyncLocalStorage } from 'node:async_hooks';
import { QueryAST, QueryInput, HookContext, ServiceObject } from '@objectstack/spec/data';
// [commit 74155c735] The defaulting node schema `fillQueryAstDefaults` runs author input
// through — the declared `.default()` stays in `packages/spec`, the engine
// only invokes it.
import {
EngineQueryOptions,
DataEngineInsertOptions,
EngineUpdateOptions,
EngineDeleteOptions,
EngineAggregateOptions,
EngineCountOptions,
type DroppedFieldsEvent,
} from '@objectstack/spec/data';
import type { WriteObservabilityOptions } from '@objectstack/spec/contracts';
// The validate-only result IS the protocol's response shape (commit 18189983d): the
// engine is what `metadata-protocol.validateData` returns, so letting the two
// drift would put a translation layer between a verdict and its contract.
import type { ValidateDataResponse } from '@objectstack/spec/api';
import { parseAutonumberFormat } from '@objectstack/spec/data';
// [#5158] Door 2's lowering sink — the SAME pair the protocol face (Door 1)
// runs, so `FilterArray` has exactly one lowering in the product.
// [ADR-0053 D-D1, amended 2026-09-30 — #5930] The shared `FilterCondition →
// FilterCondition` lowering, run once per filter position after the doors and
// after token resolution (`resolveThenLowerWhere`), so every driver and the
// in-process `having` / per-aggregation evaluator receive the lowered filter.
import { type FilterCondition, type FilterLoweringOptions } from '@objectstack/spec/data';
// [#5574] D6, executable. The ceiling and the refusal message live in
// `packages/spec/src/data/bulk-write-hook-conformance.ts` so BOTH phases and
// both verbs enforce one definition; the engine raises, the contract decides.
import { MAX_BULK_PER_ROW_HOOK_ROWS } from '@objectstack/spec/data';
// [ADR-0126 §8] The packaged-action activation ledger: its row contract, its
// stores and the engine-held projection the dispatch doors consult.
import {
ActionActivationProjection,
type ActionActivationRow,
type ActionActivationStore,
type ActionActivationWriteOptions,
} from './action-activation.js';
import {
type ComposableReadableIdsSite,
} from './filter-comparand-shape.js';
// Seek pagination for the walks that must read EVERY row — the autonumber seed
// scan is one (#6249). Shared with `summary-backfill` rather than re-rolled:
// the cursor merge is the part that is easy to get subtly wrong.
// [#25522 cut 1] The validation-message localisation helpers; the methods of the
// same names below hand each body the members it reads (`ValidationMessageHost`).
import { negotiatedMessageLocale, objectDisplayLabel, validationMessageContext } from './engine-validation-messages.js';
// [#25522 cut 2] The datasource-routing bodies; the methods of the same names
// below hand each body the members it reads (`DatasourceRoutingHost`).
import { getDriver, matchPattern, resolveDatasourceFromMapping } from './engine-datasource-routing.js';
// [#25522 cut 3] The lifecycle health bodies; the methods of the same names
// below hand each body the members it reads (`LifecycleHealthHost`).
import { checkDriversHealth, resolvePrimaryDatasource } from './engine-lifecycle-health.js';
// [#25522 cut 4] The realtime publish bodies and the event helpers only they
// call; the methods of the same names below hand each body the members it
// reads (`RealtimePublishHost`).
import { publishBulkDataEvent, publishDataEvent } from './engine-realtime-publish.js';
// [#25522 cut 5] The secret and internal-field bodies; the methods of the same
// names below hand each body the members it reads (`SecretInternalFieldsHost`).
import {
encryptSecretFields,
maskSecretFields,
omitInternalFields,
persistSecretRows,
privilegedReadDriverOptions,
refuseEmptyPasswordFields,
releaseSecretHandles,
resolveInternalField,
resolveSecret,
resolveSecretField,
stripSearchCompanionFromRead,
type PendingSecretRow,
type SecretHandleSlot,
type StoredRowsReader,
} from './engine-secret-internal-fields.js';
// [#30237, ADR-0148] The recycle bin's write side: the capture body, and the
// retention seam the host hands over (`RecycleBinCaptureHost`).
import { openRecycleBinCapture, type RecycleBinCapture } from './recycle-bin/capture.js';
import { emptyRecycleBin, purgeRecycleBinEntry, type RecycleBinRemovalOptions } from './recycle-bin/purge.js';
import type { RecycleBinRetentionSettings } from './recycle-bin/retention.js';
import { restoreRecycleBinEntry, type RecycleBinRestoreOptions, type RecycleBinRestoreResult } from './recycle-bin/restore.js';
import { listRecycleBin, type RecycleBinDeleteObservability, type RecycleBinListOptions, type RecycleBinListResult } from './recycle-bin/list.js';
// [#25522 cut 6] The predicate-write hook dispatch bodies; the methods of the
// same names below hand each body the members it reads (`HookDispatchHost`).
import {
assertBulkPerRowHookBudget,
buildPerRowAfterContexts,
dispatchPerRowBeforeHooks,
inAfterAbortUnit,
} from './engine-hook-dispatch.js';
// [#25522 cut 7] The raw-command and transaction-routing bodies; the methods of
// the same names below hand each body the members it reads (`ExecuteTransactionsHost`).
import { enforceTransactionOrigin, execute, warnTransactionUnsupported } from './engine-execute-transactions.js';
// [#25522 cut 8] The compatibility-API bodies; the methods of the same names
// below hand each body the members it reads (`CompatibilityApiHost`).
import { applyPublishedColumnChanges, getConfigs, introspectDatasource, registerObject, removePackage, syncObjectSchema, syncSchemas, type PublishedColumnChangeReport } from './engine-compatibility-api.js';
// [#25522 cut 9] The hook-context caller-envelope builders; the methods of the
// same names below call them, and none of the bodies reads a member.
import { buildEvalUser, buildProvenance, buildSession, buildUser } from './engine-execution-plumbing.js';
// [#25522 cut 10] The write path's reference check and the caller's read of a
// master-detail header; the methods of the same names below hand each body the
// members it reads (`ReferentialIntegrityHost`).
import { assertReferencesResolve, masterDetailHeadersCallerReads, type StoredReferenceRows } from './engine-referential-integrity.js';
// [#25522 cut 11] File-field hydration on read; the methods of the same names
// below hand each body the members it reads (`FileReferenceHydrationHost`).
import { callerMayReadSysFile, readParentDerivedFiles, resolveFileReferences, servableFileRows, serveRefusedFileHydration } from './engine-file-reference-hydration.js';
// [#29460] A `referenceNameVisible` reference's refused targets served by name
// and id on the expanded read; the method of the same name below hands the body
// the members it reads (`ReferenceNameVisibleHost`).
import { formulaReadsReference, serveReferenceNames } from './engine-reference-name-visible.js';
// [#25522 cut 12] The driver options every driver call receives, and the tenancy
// posture and Layer 0 verdict they are scoped by; the methods of the same names
// below hand each body the members it reads (`DriverOptionsHost`).
import { buildDriverOptions, driverReadScope, driverWriteTarget, engineLayer0Verdict, resolveEnginePosture, wallExemptedOperation } from './engine-driver-options.js';
// [#25522 cut 13] The `sys_migration` flag reads, the certification question a
// driver is handed, and the admitted-violation tally and boot advisory; the
// methods of the same names below hand each body the members it reads (`MigrationFlagsHost`).
import { announceOpenMigrationGates, isOrganizationOwnershipCertified, isValueShapesMigrationVerified, noteAdmittedValueShapeViolation, readFileReferencesFlagRow, readMigrationFlagVerified, supplyTenantKeyCertifiedResolver, wasDatastoreCreatedFromEmpty } from './engine-migration-flags.js';
import { ExecutionContext, type InstalledPackageSource } from '@objectstack/spec/kernel';
// [#27884] The stored-row read gate, registered on the family's tables below.
// Imported from spec directly rather than through `@objectstack/core`'s
// re-export block: that block is labelled backward-compatibility, and this
// contract is new (#5945).
import type { IPubSub, IScopedContext, IScopedObjectRepository, IntrospectedSchema as SpecIntrospectedSchema } from '@objectstack/spec/contracts';
// [#20157] The judge-only filter-admission member's verdict and options.
import type { EngineFilterJudgement, EngineFilterJudgementOptions, InternalFieldEvaluationOptions, InternalFieldEvaluationQuery } from '@objectstack/spec/contracts';
import {
IDataDriver,
IDataEngine,
type IObjectQLEngine,
type EngineTransactionInfo,
type EngineTransactionOptions,
Logger,
type PackageScopedHolderSource,
RUNTIME_COMPATIBILITY_PACKAGE_ID,
type RetryOptions,
} from '@objectstack/core';
import { WriteEpoch } from './write-epoch.js';
import { SummaryRecomputeError, type SummaryRecomputeFailure } from './summary-errors.js';
import { TransactionUnsupportedError } from './transaction-errors.js';
import {
type SummaryDescriptor,
} from './summary-aggregate.js';
import { refreshSummariesExtendedBy, summaryRefreshesSettled, type SummaryEnableRefreshReport } from './summary-enable-refresh.js';
import {
DriverConnectError,
DatasourceUnavailableError,
type DriverHealth,
type DatasourceUnavailableInfo,
type DatasourceUnavailableKind,
type PrimaryDatasourceVerdict,
} from './driver-connect-errors.js';
// [#5979] The ONE shared "which read failure is benign?" predicate (#4825
// family). Imported from the leaf `/errors` subpath — which exists precisely
// so a cross-package consumer gets the 40-line predicate without the manager,
// the loaders or the YAML/filesystem machinery behind `@objectstack/metadata`'s
// root entry. Asking the shared predicate rather than hand-rolling a
// `code === '42P01'` test here is load-bearing, not stylistic: a second
// vocabulary of "benign driver error" is the exact debt that module exists to
// retire, and `check:durability-log-level` exempts only this declared name.
// [#25522 cut 17] The registration door's forward conversion, the
// nested-plugin registration and its navigation resolution; the methods of the
// same names below hand each body the members it reads
// (`PackageRegistrationHost`). Imported where this file imported
// `@objectstack/metadata-core`, which only those bodies read, so the
// evaluation order of every module and external package is what it was.
import { convertPackageBodyForward, registerPlugin, resolveNavObjectNames } from './engine-package-registration.js';
// [#6806] The ONE shared "is this driver error a unique-constraint violation?"
// predicate, and its narrower companion "which column conflicted" (#6250 /
// #6544, both landed in `@objectstack/types`). The engine's autonumber
// collision resync asks exactly the two questions those exports were named to
// answer, so it asks THEM — hand-writing a fifth dialect word-list inside the
// engine is the consumer-side tolerant parsing PD #12 forbids and precedent
// #5841 retired.
import { AssignmentRuleEvaluator, type AssignmentQueueService } from './assignment-rules.js';
// [#8682] The write-path loggers' redaction — bound values never reach the log.
// [#21274] …and its boundary face — nor the error that leaves the engine.
// [#21385] It lives in `@objectstack/types` now, so `driver-sql`'s own log lines
// call the same cut; nothing about it changed in the move.
// [#8844] The runtime half of #8686's ruling: a system-context write on a
// tenant-scoped object resolves the install's organization the way a session
// write does, or is refused rather than filed under the `__global__`
// pseudo-tenant. The decision is a pure function of measured facts; this file
// supplies the facts and turns a `refuse` into the throw.
import {
type SystemWriteOrganizationDecision,
} from './tenancy/system-write-organization.js';
import {
type TenancyPosture,
type TenantLayer0Verdict,
postureUsesUnionScope,
} from '@objectstack/spec/security';
/**
* Per-row outcome of {@link ObjectQL.insertMany} (framework#3172). One entry
* per input row, in input order: written rows carry the after-hook record,
* failed rows carry the per-row error (validation / autonumber / encryption).
*
* [#20922] A written row also carries `droppedFields`: the caller-supplied
* fields the engine LEGALLY stripped from THAT row, one `DroppedFieldsEvent`
* per reason — the per-row channel, recorded at the strips. Present only when
* at least one field was taken from the row. The batch-level `onFieldsDropped`
* events are unchanged and still name no row; this key is not a resolution of
* them. A failed row carries none: its write did not complete.
*/
export type InsertManyRowOutcome =
| { ok: true; record: any; droppedFields?: DroppedFieldsEvent[] }
| { ok: false; error: unknown };
import { IRealtimeService } from '@objectstack/spec/contracts';
import type { ICryptoProvider } from '@objectstack/spec/contracts';
// [#25522 cut 18] `count` and `aggregate()`'s credential guard
// (`rejectCredentialAggregation`); the methods of the same names below hand
// each body the members it reads (`CountAggregateHost`).
import { count, rejectCredentialAggregation } from './engine-count-aggregate.js';
// ADR-0100: the credential-column guard's filter / sort half, beside the
// aggregate half above — one collector, one envelope.
import {
type HomeAmountPlanEntry,
type HomeAmountReads,
type HomeAmountServing,
type HomeLocalizationResolver,
} from './home-amount-projection.js';
import { SchemaRegistry, type ArtifactInstallScope } from './registry.js';
import { type EvalError, type EvalOptionLabels, type EvalPermissions } from '@objectstack/formula';
// [commit 3c1bbd2a8] The ONE spelling of "which object does an aggregated `defineView`
// container bind to", imported rather than re-spelled — from the LEAF subpath,
// for the reason the `/errors` import above states (commit 3bd9b3498). See
// `resolveMetadataItemName` below for why this registrar lost its fourth copy.
// [#20331] The divergent view-container `name` refusal — the ONE judge this
// registrar and `os validate` both call.
import { type BindHooksOptions } from './hook-binder.js';
import type { AdmittedValueShapeViolation, AdmittedValueShapeViolationSink, ValidationMessageContext } from './validation/record-validator.js';
import type { RelatedRecordBinding } from './validation/rule-validator.js';
import { stripReadonlyFields, staticReadonlyInsertSubject } from './validation/rule-validator.js';
// [#14088] The before-phase write recorder — the provenance channel the static
// `readonly` strip needs to tell a hook's write from a caller's echo of the
// SAME value. Armed and sealed in `update()`; the module owns the argument for
// why neither end may move.
// [commit 706ad0fcc] The hide pass's other half: when a hook faults reaching THROUGH a
// key that pass withheld, this names the key, says the platform withheld it,
// and points at `ctx.previous` — the module owns the measurement and the
// reason the explanation cannot be composed any further downstream.
import { UnscopedHookApi, SEED_USER_GRANTS, APP_AUTHORED_HOOK_API, type HookRunAs, type HookRunAsRef, type RunAsDerivableApi } from './hook-run-as.js';
import { DETACHED_HOOK_RUN } from './unit-detach.js';
// [#6457] The master-detail header a `parent`-scoped predicate reads is made
// total over the MASTER's declared fields before it leaves this engine — the
// same helper every other server seam materialises with (#1871/#4649/#4953).
// [#21571] The declared column set — the read verbs' default projection, their
// explicit-projection filter and the write path's undeclared-key door, one list.
// [#21777] "Is this schema the remote's?" One predicate, shared with the boot sync.
// [#21910, #21918] And its injected-column refinement, which both cascade walks ask.
// [#27277] The correctness floor over a plugin driver on an external datasource.
// [#25522 cut 14] The master-detail landing, the preview's parents and the
// related reads a validation rule makes; the methods of the same names below
// hand each body the members it reads (`MasterDetailRelatedHost`). Imported after
// every module those bodies import, so the engine's module evaluation order
// is what it was.
import { priorMasterIdsCallerReads, resolveOneHopRelated, resolvePredicateRelated, resolvePreviewParents, settleMasterDetailLanding } from './engine-master-detail-related.js';
// [#25522 cut 15] The `ReadableIds` chain composition, the controlled-by-parent
// boot screen, and the permission and formula resolutions an operation shares;
// the methods of the same names below hand each body the members it reads
// (`ReadableIdsPermissionFormulaHost`). Imported after every module those bodies import, so
// the engine's module evaluation order is what it was.
import { composeReadableIdsChain, findUnservableControlledByParentMasters, permissionResolution, readableIdsScopeOf, reportFormulaFault, resolveDefaultPermissions, resolveFormulaPermissions, resolveOptionPermissions } from './engine-readable-ids-permission-formula.js';
// [#25522 cut 19] The delete cascade's collection walk, the in-cascade
// `restrict` judge, the `DELETE_RESTRICTED` refusal, the reference-probe
// filter and the reference-check elevation record; the methods of the same
// names below hand each body the members it reads (`DeleteCascadeHost`).
// Imported after every module those bodies import, so the engine's module
// evaluation order is what it was.
// [#28001] …and the object-level closure of that walk the metadata read serves.
import { collectCascadeDeleteSet, deleteRestrictedError, recordReferenceCheckElevation, referenceProbeFilter, refuseRestrictsInsideOwnCascade } from './engine-delete-cascade.js';
// [#25522 cut 16] The write preview's body; `validate` below hands it the
// members it reads (`ValidateHost`). Imported after every module that body
// imports, so the engine's module evaluation order is what it was.
import { validate } from './engine-validate.js';
// [#32768] The write-free `readonlyWhen` judgement's body; `judgeFieldWriteLock`
// below hands it the members it reads (`FieldWriteLockHost`).
import { judgeFieldWriteLock, type FieldWriteLock } from './engine-field-write-lock.js';
// [#25522 cut 20] The `where`-lowering bodies (`QueryLoweringHost`), imported
// after every module they import, so module evaluation order is unchanged.
import { lowerRelationConditions, resolveSearchQueryableFields, resolveWhereTokens } from './engine-query-lowering.js';
import {
auditDanglingReferences,
type DanglingReferenceAuditOptions,
type DanglingReferenceReport,
} from './integrity/dangling-reference-audit.js';
// [#29986 codemod] The top-level declarations that moved whole to `engine-top-level.ts`, as this file still reads them.
import {
DISPATCHABLE_HOOK_EVENTS, SECURITY_SERVICE_SOURCE_SLOT, assertDispatchableHookEvent, assertValidHookExcludeObjects,
planStoredExpressions,
} from './engine-top-level.js';
import type {
AdmittedValueShapeViolationTally, AutonumberReaders, CascadeDeleteSet, CascadeIssuedDelete, DatasourceDef,
EngineMiddleware, EngineReadOptions, FieldOwnedFileReadAuthorizer, FormulaFaultSink, FormulaPlanEntry,
FormulaRelated, FunctionEntry, FunctionRegistrationOptions, HeldFileResolver, HookEntry, HookHandler,
IssuedAutonumber, MigrationFlagRead, OperationContext, PermissionResolution, ReadableIdsChain, ReadableIdsSecurity,
ReadableIdsSecurityResolution, TransactionScope, UnservableControlledByParentMaster, WriteWallVerdict,
} from './engine-top-level.js';
// [#29986 codemod] Re-exported by name, so every importer of `./engine.js` reads what it read.
export {
type AdmittedValueShapeViolationTally, type CascadeDeleteSet, type DatasourceDef, ENGINE_COUNT_OPTION_KEYS,
ENGINE_OPTION_KEY_SETS, ENGINE_WHERE_SLOTS, type EngineMiddleware, type EngineReadOptions,
type FieldOwnedFileReadAuthorizer, type FormulaPlanEntry, type FunctionEntry, type FunctionRegistrationOptions,
HOOK_EVENT_DISPATCH_VOCABULARY, type HeldFileResolver, type HookEntry, type HookHandler, type MigrationFlagRead,
type OperationContext, type PermissionResolution, type PostHookWriteImageCheck, type ReadableIdsChain,
type ReadableIdsSecurity, SECURITY_SERVICE_SOURCE_SLOT, type UnservableControlledByParentMaster,
type WriteWallRowVerdict, type WriteWallVerdict, assembledViewItemRefusal, cascadeMemberKey, cascadeSetAdd,
cascadeSetHas, collectionItemOwnerStampRefusal, declaredDatetimeLowering, declaredMultiValued, droppedFieldEvents,
evaluateFormulaField, foldEngineOptionAliases, hookMatchesObject, insertStaticReadonlySubject, isExpressionDefault,
lowerWhereFilterArray, masterIdOf, mergeReadContext, packageBodyCollectionRefusal,
packageBodyObjectAndAppOwnerStampRefusal, packageBodySeedDataRefusal, permissionSetOwnerRegistrationRefusal,
registerAppNotingStamp, rejectUnknownEngineOptions, relationSitesOf, resolveThenLowerWhere, servedAsStored,
shouldSkipStateMachine, stampObjectPackage, stampPackage, staticReadonlyStoredView, stripComputedWriteFields,
undeclaredRelatedFields, undeclaredWriteFieldErrors, updateStaticReadonlySubject, viewsEntryNotContainerRefusal,
writeFailureLogMeta,
} from './engine-top-level.js';
// [#29986 codemod] Class head: units, hooks, functions, body runners, hook dispatch: the methods of the same names below hand the bodies what they read (`HooksAndFunctionsHost`).
import { HooksAndFunctionsFacet } from './engine-hooks-and-functions.js';
// [#29986 codemod] Action system and packaged-action activation: the methods of the same names below hand the bodies what they read (`ActionsHost`).
import { ActionsFacet, type ActionHandlerEntry, type ExecuteActionOptions } from './engine-actions.js';
// [#29986 codemod] Registration seams, readable-ids security, formula and default permissions: the methods of the same names below hand the bodies what they read (`SecurityResolversHost`).
import { SecurityResolversFacet } from './engine-security-resolvers.js';
// [#29986 codemod] Authz invalidation, middleware, session, driver options, posture, organization probe: the methods of the same names below hand the bodies what they read (`MiddlewareAndContextHost`).
import { MiddlewareAndContextFacet } from './engine-middleware-and-context.js';
// [#29986 codemod] Field defaults and autonumbers: the methods of the same names below hand the bodies what they read (`DefaultsAndAutonumbersHost`).
import { DefaultsAndAutonumbersFacet } from './engine-defaults-and-autonumbers.js';
// [#29986 codemod] Package, app, plugin, driver and datasource registration: the methods of the same names below hand the bodies what they read (`RegistrationHost`).
import { RegistrationFacet } from './engine-registration.js';
// [#29986 codemod] Realtime, i18n, home amounts, validation messages, references, master-detail: the methods of the same names below hand the bodies what they read (`ReferencesAndMasterDetailHost`).
import { ReferencesAndMasterDetailFacet } from './engine-references-and-master-detail.js';
// [#29986 codemod] Crypto, secrets, internal fields, schema and datasource routing, init: the methods of the same names below hand the bodies what they read (`SecretsAndRoutingHost`).
import { SecretsAndRoutingFacet } from './engine-secrets-and-routing.js';
// [#29986 codemod] Migration flags, value-shape deviations, creation attestations, destroy: the methods of the same names below hand the bodies what they read (`MigrationStateHost`).
import { MigrationStateFacet } from './engine-migration-state.js';
// [#29986 codemod] Summary indexes, related-record expansion, file and reference hydration: the methods of the same names below hand the bodies what they read (`SummariesAndExpansionHost`).
import { SummariesAndExpansionFacet } from './engine-summaries-and-expansion.js';
// [#29986 codemod] Query lowering, search, find and findOne: the methods of the same names below hand the bodies what they read (`FindHost`).
import { FindFacet } from './engine-find.js';
// [#29986 codemod] Write preparation and insert: the methods of the same names below hand the bodies what they read (`InsertHost`).
import { InsertFacet } from './engine-insert.js';
// [#29986 codemod] Update: the methods of the same names below hand the bodies what they read (`UpdateHost`).
import { UpdateFacet } from './engine-update.js';
// [#29986 codemod] Cascade and referential delete planning: the methods of the same names below hand the bodies what they read (`CascadePlanningHost`).
import { CascadePlanningFacet } from './engine-cascade-planning.js';
// [#29986 codemod] Delete, count, aggregate and execute: the methods of the same names below hand the bodies what they read (`DeleteAndAggregateHost`).
import { DeleteAndAggregateFacet } from './engine-delete-and-aggregate.js';
// [#29986 codemod] Transactions: the methods of the same names below hand the bodies what they read (`TransactionsSectionHost`).
import { TransactionsSectionFacet } from './engine-transactions-section.js';
// [#29986 codemod] Compatibility / convenience API: the methods of the same names below hand the bodies what they read (`CompatibilitySectionHost`).
import { CompatibilitySectionFacet } from './engine-compatibility-section.js';
// [#29986 codemod] The facets' hosts, one per engine, which the static block at the end of the class builds.
import {
actionsHost, cascadePlanningHost, compatibilitySectionHost, defaultsAndAutonumbersHost, deleteAndAggregateHost,
findHost, hooksAndFunctionsHost, insertHost, middlewareAndContextHost, migrationStateHost,
referencesAndMasterDetailHost, registrationHost, secretsAndRoutingHost, securityResolversHost,
summariesAndExpansionHost, transactionsSectionHost, updateHost,
} from './engine-facet-hosts.js';
// [#30052 codemod] Repository bound to one object and one execution context: the methods of the same names on `ObjectRepository` hand the bodies what they read (`ObjectRepositoryHost`).
import { ObjectRepositoryFacet } from './engine-object-repository.js';
// [#30052 codemod] Scoped execution context: repositories, elevation, transactions: the methods of the same names on `ScopedContext` hand the bodies what they read (`ScopedContextHost`).
import { ScopedContextFacet } from './engine-scoped-context.js';
// [#30052 codemod] The scoped facets' hosts, one per instance, which each class's static block builds.
import { objectRepositoryHost, scopedContextHost } from './engine-scoped-hosts.js';
import { captureStoredExpressions, type StoredExpressionCapture } from './stored-expression-backfill.js';
// [#29986 codemod] The statics of `ObjectQL` its facet modules read, private ones included, as
// the class declares them (an indexed access on the class). The static block at the end of
// the class fills `ObjectQLStatics` with forwarders: a method is called on the class at
// call time, a field or accessor is read when the body reads it. A facet module imports
// `ObjectQLStatics` AS `ObjectQL`, so each moved body reads `ObjectQL.x` unedited;
// `index.ts` re-exports neither, so neither reaches the package.
export interface ObjectQLStaticsHost {
readonly MAX_CASCADE_DEPTH: (typeof ObjectQL)['MAX_CASCADE_DEPTH'];
readonly MAX_EXPAND_DEPTH: (typeof ObjectQL)['MAX_EXPAND_DEPTH'];
readonly REFERENCE_PROBE_BATCH: (typeof ObjectQL)['REFERENCE_PROBE_BATCH'];
readonly coveredValueFieldPresence: (typeof ObjectQL)['coveredValueFieldPresence'];
readonly homeAmountOrganizationOf: (typeof ObjectQL)['homeAmountOrganizationOf'];
readonly keepsOrganizationReference: (typeof ObjectQL)['keepsOrganizationReference'];
readonly mediaFieldPresence: (typeof ObjectQL)['mediaFieldPresence'];
readonly organizationCountContext: (typeof ObjectQL)['organizationCountContext'];
readonly outlivesOrganization: (typeof ObjectQL)['outlivesOrganization'];
readonly referenceCheckContext: (typeof ObjectQL)['referenceCheckContext'];
readonly remainderAfterMemberRemoval: (typeof ObjectQL)['remainderAfterMemberRemoval'];
readonly storedReferenceIncludes: (typeof ObjectQL)['storedReferenceIncludes'];
}
export const ObjectQLStatics = {} as ObjectQLStaticsHost;
export class ObjectQL implements IObjectQLEngine {
/**
* Ambient transaction store (ADR-0034). While a `transaction()` callback
* runs, the active transaction handle lives here so that EVERY data
* operation — including internal reads done during a write (reference
* checks, hooks, expand) — automatically binds to the same connection
* instead of asking the pool for another one and deadlocking on the
* single-connection SQLite pool.
*/
private readonly txStore = new AsyncLocalStorage<{
transaction: unknown;
/**
* Which driver actually owns this transaction, when the engine opened it
* (#4619). `transaction()` covers the DEFAULT datasource only — a caveat
* that is part of the declared contract (ADR-0119 D1) — so a write routed
* elsewhere by `setDatasourceMapping` runs OUTSIDE it and cannot be rolled
* back with it. Carrying the owner here is what lets the write path SAY so
* ({@link enforceTransactionOrigin}) — and, since #5351, to DECIDE what
* happens to it: a business write is refused, a system ledger is carved out.
*
* Absent on the sandbox runner's explicitly-threaded handles (the
* `beginTransaction`/`commit`/`rollback` trio never POPULATES this store —
* since #6406 it reads it, to join an ambient transaction, but a
* transaction the trio opens still cannot be published: there is no closure
* spanning begin→commit to hand `run`) and on any store entry an outside
* caller populated, so every reader must treat it as optional.
*/
scope?: TransactionScope;
}>();
/**
* [#22855] The units {@link runOpenedUnit} published, keyed by their handle.
* The value is the very entry {@link txStore} holds, so the one write that
* closes a unit answers both of its readers: the ambient one finds the entry
* empty, and {@link buildDriverOptions} looks an explicitly threaded handle up
* here ({@link isClosedUnitHandle}). Weak, so a finished unit's handle stays
* collectable.
*/
private readonly openedUnits = new WeakMap<object, { transaction: unknown }>();
/**
* [#22305] The {@link CascadeDeleteSet} of the by-id cascade delete in
* progress, ambient for the same reason as {@link txStore}: the cascade
* recurses through the public `delete()`, and each level must judge its
* refusals against the set its root collected. A context key would be the
* other carrier, and it is not used: it would turn a caller's absent context
* into a present one on every nested delete.
*/
private readonly cascadeDeleteSets = new AsyncLocalStorage<CascadeDeleteSet>();
/**
* [#23221] The child delete {@link walkReferencingRelations} is issuing right
* now, so that `delete()` can tell the cascade's own child delete from every
* other delete and project the fact onto the DECLARED
* `HookContext.referentialCascadeDelete` (see
* {@link claimReferentialCascadeDelete}).
*
* Ambient, for {@link cascadeDeleteSets}' reason — a context key would change
* what the child delete is handed (where no transaction is opened, an absent
* caller context would become a present one, and both `buildSession` and
* `buildHookApi` branch on its absence) — and for one more
* the update twin's `__referentialFieldClear` never had to weigh, because its
* envelope semantics predated its declared projection: the child delete's
* context is the very object `buildHookApi` hands to `ScopedContext`, so a
* key stamped on it would ride into every write that child's hooks issue
* through `ctx.api`, and a hook's own delete during the cascade would read
* as cascade-issued. Keyed on the exact object and id the walk issues, and
* claimed once, the marker reaches that one delete's dispatches and no other.
* Engine-private: nothing a request carries can name a record into it.
*/
private readonly cascadeIssuedDeletes = new AsyncLocalStorage<CascadeIssuedDelete>();
private drivers = new Map<string, IDataDriver>();
private defaultDriver: string | null = null;
private logger: Logger;
/**
* Datasources already reported by {@link warnTransactionUnsupported}, so the
* "no `beginTransaction`" degrade says its piece ONCE per engine instance per
* driver instead of once per `transaction()` call (#4619). Test doubles and
* foreign engines hit that path on every call; a per-call warning would be
* skimmed, which is the same unreadability that made the #4420 `warn`
* worthless.
*/
private readonly transactionUnsupportedReported = new Set<string>();
/** [#25073] Objects already reported by {@link warnAutonumberReadersUnserved}: once per engine instance. */
private readonly autonumberReadersUnservedReported = new Set<string>();
/**
* Objects already reported by {@link warnCascadeNotAtomic} — the `'split'`
* verdict of {@link planCascadeAtomicity} — so a cascade that cannot be one
* unit of work says so ONCE per engine instance per object rather than on
* every delete (#7413). Same "say it once" discipline, and same reason, as
* {@link transactionUnsupportedReported} above.
*/
private readonly cascadeNotAtomicReported = new Set<string>();
// Datasource mapping rules (imported from defineStack)
private datasourceMapping: Array<{
namespace?: string;
package?: string;
objectPattern?: string;
default?: boolean;
datasource: string;
priority?: number;
}> = [];
// Package manifests registry (for defaultDatasource lookup)
private manifests = new Map<string, any>();
// [#28534] Where each ADR-0130 residual owner came from — see
// {@link recordResidualOwner}.
private readonly residualOwnerSources = new Map<string, 'code' | 'marketplace'>();
/**
* [#28534] Record the origin of an artifact's RESIDUAL owner: the id the
* residual rule files a multi-package stack's unclaimed top-level items
* under (`unclaimedTopLevel`, `@objectstack/metadata`), as the door that
* registered the artifact states it — `'code'` for the deployment's own
* boot, `'marketplace'` for an install.
*
* The residual is not a package, so no package row records that id (unless
* a body carries it, and then the body's row answers), yet its items wear it
* as their `_packageId`. Without this record a reader asking an item's
* origin could not tell the host's own residual from an installed bundle's.
* Called by the `manifest` service, the one place that knows both the
* residual's id and the door's statement. Once an id is recorded as
* `'marketplace'` it stays so for this engine: an install can never turn
* into the host's own by re-registering under the same id.
*/
recordResidualOwner(ownerId: string, source: 'code' | 'marketplace'): void {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.recordResidualOwner.call(hooksAndFunctionsHost.of(this), ownerId, source);
}
/**
* [#28534] The origin {@link recordResidualOwner} recorded for a residual
* owner id, or `undefined` when no artifact this engine registered named it
* as its residual's owner.
*/
residualOwnerSource(ownerId: string): 'code' | 'marketplace' | undefined {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.residualOwnerSource.call(hooksAndFunctionsHost.of(this), ownerId);
}
// Datasource definitions by name (ADR-0015): carries schemaMode +
// external.allowWrites so the write gate (Gate 3) can enforce federation
// ownership, and external.credentialsRef so a sys_secret reference sweep can
// see the handle a code-declared datasource holds. Populated from manifests
// in registerApp and via registerDatasourceDef. Absent entry ⇒ treated as
// managed (default DB).
private datasourceDefs = new Map<string, Omit<DatasourceDef, 'name'>>();
// Declared-but-unusable datasources, keyed by name (framework#3828). Written
// by the datasource connection layer via markDatasourceUnavailable; read only
// by getDriver, to explain a missing driver instead of blaming a typo. Empty
// is the normal state — an entry here means a connect was refused or failed.
private unavailableDatasources = new Map<string, DatasourceUnavailableInfo>();
// Per-object hooks with priority support
private hooks: Map<string, HookEntry[]> = new Map([
['beforeFind', []], ['afterFind', []],
['beforeInsert', []], ['afterInsert', []],
['beforeUpdate', []], ['afterUpdate', []],
['beforeDelete', []], ['afterDelete', []],
]);
// Middleware chain (onion model)
private middlewares: Array<{
fn: EngineMiddleware;
object?: string;
}> = [];
// Action registry: key = "objectName:actionName" — the UNQUALIFIED slot, what
// a call that names no package runs ([ADR-0150 D5, #31697]: two packages
// on one key, and a package beside host code or a plugin on the object-less
// key, are refused, `executeAction`).
private actions = new Map<string, ActionHandlerEntry>();
// [ADR-0150 D4, #31673] The action engine keyed `(package, objectName, name)`:
// package coordinate (`actionHandlerCoordinate`) → "objectName:actionName" →
// that package's handler. A call that names its package reads it.
private packageActions = new Map<string, Map<string, ActionHandlerEntry>>();
/**
* [ADR-0126 §8] The packaged-ACTION activation ledger's local projection —
* which declared actions this installation has switched OFF.
*
* It sits beside the handler registry above deliberately: the ledger governs
* what that map is allowed to dispatch, and ADR-0110 D5 already settled that
* action-adjacent boot work belongs to the engine plugin (the one component
* unconditionally present wherever actions execute). Hydrated at boot by
* `ObjectQLPlugin`; consulted by the dispatch doors through
* {@link isActionEnabled}. See `./action-activation.ts` for the row contract
* and for why identity is the declarative action NAME.
*/
private readonly actionActivation = new ActionActivationProjection();
// Function registry: name → handler, each entry stamped with its owning
// package. Used by `bindHooksToEngine` to resolve string-named hook
// handlers (the JSON-safe form) — only against entries the hook's OWN
// package registered. Populated by `defineStack({ functions })` via
// `AppPlugin`, or directly via `engine.registerFunction(...)`.
private functions = new Map<string, FunctionEntry>();
// [ADR-0150 D4, #31716] The same registrations by holder: function name →
// registering package (the owner read as its package id; `null` for an
// owner-less registration) → that package's entry. `functions` above keeps
// one entry per name, the last-registered; this keeps every holder, so a
// referrer's function can be resolved in its package
// (`resolvePackageScopedFunction` over `functionHoldersOf`).
private functionHolders = new Map<string, Map<string | null, FunctionEntry>>();
// Realtime service for event publishing
private realtimeService?: IRealtimeService;
// i18n service backing validation-message + field-label localization (#3957).
// Optional: without it, messages render from the built-in catalog against the
// declared labels.
private i18nService?: {
t?: (key: string, locale: string, params?: Record<string, unknown>) => string;
// [#15757] `II18nService` requires `getLocales()`; it is optional HERE for
// the same reason `t` is — the setter accepts any partial shim, and a shim
// that cannot say what it holds is simply not negotiated against.
getLocales?: () => string[];
// [#26608] What a formula's `label()` is translated through: the bundle
// and the declared locale chain, read as the metadata route reads them
// (`formula-option-labels.ts`). Optional for the same reason.
getTranslations?: (locale: string) => Record<string, unknown>;
getFallbackLocale?: () => string | undefined;
getDefaultLocale?: () => string | undefined;
getSourceLocale?: () => string | undefined;
};
// Crypto provider backing `secret`-typed fields. Optional: when absent,
// writing an object that declares a secret field fails closed (never
// persists cleartext). Injected by the host via setCryptoProvider().
private cryptoProvider?: ICryptoProvider;
// [#8022] Listeners notified when a crypto provider is (re)registered.
// Server-side consumers that dereference a secret at BOOT — the webhook
// auto-enqueuer's subscription cache is the one this was built for — run
// inside `kernel:ready`, which every host completes BEFORE its composition
// root injects a provider. Their first read therefore fails closed against a
// capability that is about to exist, and without a notification the only way
// back is to poll. The engine is the sole party that knows the moment it
// arrives, so the notification belongs here.
private readonly cryptoProviderListeners = new Set<() => void>();
// [ADR-0105 D2 / #3623] Posture accessor for driver-scope widening under the
// `group` posture. Injected by SecurityPlugin via setTenancyPostureProvider();
// absent = equality scoping (fail toward isolation).
private tenancyPostureProvider?: () => string | undefined;
// [#8844] The install's organizations, capped at two — memoised across system
// writes and dropped whenever `sys_organization` is written through this
// engine. See `probeInstallOrganizations` for the stale window this accepts.
private organizationProbeMemo?: readonly string[];
// Per-engine SchemaRegistry instance.
//
// Historically SchemaRegistry was a process-wide singleton of static state,
// which broke multi-environment servers: a project kernel would inherit every
// object registered by the control plane (e.g. sys_metadata), and
// getDriver()'s owner lookup would route CRUD to the wrong database. Each
// engine now owns its registry so kernels are fully isolated.
private _registry: SchemaRegistry = new SchemaRegistry();
constructor(hostContext: Record<string, any> = {}) {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
this.logger = HooksAndFunctionsFacet.constructLogger(hostContext);
HooksAndFunctionsFacet.construct.call(hooksAndFunctionsHost.of(this));
}
/**
* Service Status Report
* Used by Kernel to verify health and capabilities.
*/
getStatus(): {
name: "data";
status: string;
version: string;
features: string[];
} {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts`.
return HooksAndFunctionsFacet.getStatus();
}
/**
* Expose the SchemaRegistry for plugins to register metadata.
*
* Returns the per-engine instance, NOT the class. Each ObjectQL engine
* owns its registry so multi-environment kernels remain isolated.
*/
get registry(): SchemaRegistry {
return this._registry;
}
/**
* Register a hook
*
* [#17713] `event` must be one of {@link DISPATCHABLE_HOOK_EVENTS}, or a name
* outside the engine's lifecycle namespace entirely (a custom event a plugin
* dispatches itself through {@link ObjectQL.triggerHooks}). An engine
* lifecycle name the engine never dispatches — `beforeCount`, `beforeFindOne`
* and their siblings — is REFUSED here rather than registered inert; see
* {@link assertDispatchableHookEvent}.
*
* @param event The event name (e.g. 'beforeFind', 'afterInsert')
* @param handler The handler function
* @param options Optional: target object(s), objects to exclude, and priority
*/
registerHook(event: string, handler: HookHandler, options?: {
object?: string | string[];
/**
* [#5928] Object name(s) subtracted from what `object` admits — the way to
* say "global, except these". See {@link HookEntry.excludeObjects} for why
* an allow list cannot express it, and
* {@link assertValidHookExcludeObjects} for the two refused shapes.
*/
excludeObjects?: string | string[];
priority?: number;
packageId?: string;
/**
* [#9719, widened by #9974] Opt-in whole-operation dispatch for an
* UNSCOPED predicate write (`multi: true`, no `where`) — see
* {@link HookEntry.dispatchUnscopedMultiWrite}. Valid on `beforeUpdate` /
* `beforeDelete` registrations only.
*/
dispatchUnscopedMultiWrite?: boolean;
/** Original metadata Hook definition (set by `bindHooksToEngine`). */
meta?: any;
/** Stable name from metadata (set by `bindHooksToEngine`). */
hookName?: string;
}): void {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.registerHook.call(hooksAndFunctionsHost.of(this), event, handler, options);
}
/**
* Remove all hooks registered under a given `packageId`. Used by
* `bindHooksToEngine` to make re-binding (hot reload, app reinstall)
* idempotent, and by app uninstall flows.
*/
unregisterHooksByPackage(packageId: string): number {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.unregisterHooksByPackage.call(hooksAndFunctionsHost.of(this), packageId);
}
/**
* Register a named function handler that can later be referenced by
* string from a `Hook.handler` field, an `Action.target`, or a flow
* `script` node's `config.function`. This is the JSON-safe form of
* handler binding — declarative metadata persisted to disk or shipped
* over the wire only carries the name. A `Hook.handler` reaches the entry
* only from a hook of the same `packageId` (`bindHooksToEngine`).
*
* The third parameter accepts either the owning `packageId` (its original
* shape, unchanged for every existing caller) or a
* {@link FunctionRegistrationOptions} record that also carries what the
* function DECLARES about itself — today its data `effect` (#4396).
*/
registerFunction(
name: string,
handler: HookHandler,
packageIdOrOptions?: string | FunctionRegistrationOptions,
): void {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.registerFunction.call(hooksAndFunctionsHost.of(this), name, handler, packageIdOrOptions);
}
/**
* Look up a registered function by name, with no package: the last
* registration of the name. [ADR-0150 D3/D4, #31700, #32907; epic seat
* ruling R2-C] A name two holders hold — two packages (two namespaces may
* each bind one), or the platform (an owner-less registration) beside a
* package — is refused, `409 RESOURCE_CONFLICT` naming every holder, never
* answered with one of them, whichever registered last. [#32933] A disabled
* package is counted as a holder and never answered: a name only a disabled
* package holds answers nothing. A reader that knows its package resolves
* through {@link functionHoldersOf}.
*
* @throws {PackageScopedNameRefusedError} for a name two holders hold.
*/
resolveFunction(name: string): HookHandler | undefined {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.resolveFunction.call(hooksAndFunctionsHost.of(this), name);
}
/**
* Look up a registered function's FULL entry — the handler plus whatever it
* declared about itself (#4396). `resolveFunction` above answers "can I call
* it"; a caller that must also report what the call did (the automation
* engine's `script` node, feeding the #4354 run summary) needs the
* declaration, and reading it off the same registry keeps the two from
* drifting. Refused alike for a name two holders hold, and answers nothing
* alike for a name only a disabled package holds (above).
*
* @throws {PackageScopedNameRefusedError} for a name two holders hold.
*/
resolveFunctionEntry(name: string): Readonly<FunctionEntry> | undefined {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.resolveFunctionEntry.call(hooksAndFunctionsHost.of(this), name);
}
/**
* Every holder of the function `name` (ADR-0150 D4): each package that
* registered one under that name, with its own entry, and an owner-less
* registration as the platform's item (`platformItem`: code a plugin or
* the host registers, in every caller's reach like `sys`) — the holder set
* `resolvePackageScopedFunction` resolves a flow `script` node's function
* over, in the calling flow's package. A snapshot, taken at the call. The flow
* `script` node resolves through it (#32073), and `bindHooksToEngine` reads
* a hook's own package's entry from it. `resolveFunction` and
* `resolveFunctionEntry` answer the one last-registered entry per name, and
* refuse a name two holders hold (#31700, #32907).
*/
functionHoldersOf(name: string): PackageScopedHolderSource<Readonly<FunctionEntry>> {
// [#31716] The body lives in `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.functionHoldersOf.call(hooksAndFunctionsHost.of(this), name);
}
/**
* Remove all functions registered under a given `packageId`, from the bare
* map and the holder set ({@link functionHoldersOf}); answers how many bare
* entries left. [#32534] When the last registration of a name leaves and
* exactly one holder of it remains, the bare read answers that holder.
*/
unregisterFunctionsByPackage(packageId: string): number {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.unregisterFunctionsByPackage.call(hooksAndFunctionsHost.of(this), packageId);
}
/**
* Bind a list of declarative `Hook` metadata definitions to this engine.
*
* Convenience proxy to the canonical `bindHooksToEngine` so callers do
* not need a separate import. Use `import { bindHooksToEngine } from
* '@objectstack/objectql'` directly when you want the result object.
*/
bindHooks(hooks: any[] | undefined, opts?: {
packageId?: string;
functions?: Record<string, HookHandler>;
bodyRunner?: any;
strict?: boolean;
warnLegacyHandler?: boolean;
metrics?: any;
/** Wraps each in-process handler after its name resolves — see {@link BindHooksOptions.wrapHandler}. */
wrapHandler?: BindHooksOptions['wrapHandler'];
}): void {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.bindHooks.call(hooksAndFunctionsHost.of(this), hooks, opts);
}
/** Default hook body-runner — see {@link setDefaultBodyRunner}. */
private _defaultBodyRunner?: any;
/** Default action body-runner factory — see {@link setDefaultActionRunner}. */
private _defaultActionRunner?: (actionDef: any) => ((ctx: any) => Promise<unknown>) | undefined;
/**
* Install a default body-runner used when `bindHooks` is called without
* an explicit one. The runtime layer sets this once on each per-project
* engine so every binding path (template seed, metadata sync, AppPlugin)
* can execute hook `body.source` consistently.
*
* FIRST-WINS (#4251): "set once per engine" is this method's own contract,
* so the method enforces it — a second call is ignored and returns `false`.
* Callers used to implement the guard themselves by probing the private
* `_defaultBodyRunner` field through `any` (multiple AppPlugin instances on
* one kernel must not clobber each other's runner), which meant the
* invariant lived in every caller and belonged to none. Nobody replaces a
* runner on a live engine: every setter call site either owns a fresh
* engine or wants exactly this keep-the-first behaviour.
*
* @returns `true` when this call installed the runner, `false` when one was
* already present (kept unchanged).
*/
setDefaultBodyRunner(runner: any): boolean {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.setDefaultBodyRunner.call(hooksAndFunctionsHost.of(this), runner);
}
/** The installed default body-runner, if any — the public read the first-wins guard implies. */
getDefaultBodyRunner(): any {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.getDefaultBodyRunner.call(hooksAndFunctionsHost.of(this));
}
/**
* Install a default ACTION body-runner factory: `(actionDef) => handler |
* undefined`. The runtime layer sets this once per engine (same boot point
* as {@link setDefaultBodyRunner}) so runtime-authored `action` metadata —
* which registers through paths that have no sandbox access of their own,
* notably ObjectQLPlugin's metadata-service re-sync — can turn a declarative
* `body` into an executable `registerAction` handler. The factory returns
* `undefined` for actions it cannot run (no `body`, invalid shape), which
* callers must treat as "skip", not an error.
*
* FIRST-WINS (#4251) — same contract and rationale as
* {@link setDefaultBodyRunner}.
*
* @returns `true` when this call installed the runner, `false` when one was
* already present (kept unchanged).
*/
setDefaultActionRunner(runner: (actionDef: any) => ((ctx: any) => Promise<unknown>) | undefined): boolean {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.setDefaultActionRunner.call(hooksAndFunctionsHost.of(this), runner);
}
/** The installed default action-runner factory, if any. */
getDefaultActionRunner(): ((actionDef: any) => ((ctx: any) => Promise<unknown>) | undefined) | undefined {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.getDefaultActionRunner.call(hooksAndFunctionsHost.of(this));
}
/**
* Toggle strict hook-binding mode for this engine. When enabled, every
* subsequent `bindHooks` call rejects on the first unresolved hook
* instead of silently warning. Production runtimes should enable this.
*/
setStrictHookBinding(strict: boolean): void {
(this as any)._strictHookBinding = strict;
}
/** Toggle deprecation warnings for hooks still using legacy `handler` ref. */
setWarnLegacyHandler(warn: boolean): void {
(this as any)._warnLegacyHandler = warn;
}
/**
* Install a metrics recorder used by every subsequent `bindHooks` call.
* The recorder's methods are invoked per-execution to count outcomes
* (success / error / timeout / capability_rejected), skips, and retries.
* Defaults to no-op so the engine pays zero cost when nobody is observing.
*/
setHookMetricsRecorder(recorder: any): void {
(this as any)._hookMetricsRecorder = recorder;
}
/** Read the engine's installed metrics recorder, if any. */
getHookMetricsRecorder(): any {
return (this as any)._hookMetricsRecorder;
}
/**
* Dispatch `event` to every registered handler that covers `context.object`,
* in priority order, awaiting each in turn.
*
* ⚠️ This runs wherever the caller calls it — it does NOT wait for a commit.
* An `after*` dispatch made from inside an open transaction therefore fires
* for a write that can still be rolled back; that is the declared semantics
* (#7477), stated in full on {@link DISPATCHABLE_HOOK_EVENTS}. Anything
* added here that defers a dispatch past the enclosing unit of work would be
* changing that ruling, not implementing it.
*/
public triggerHooks(event: string, context: HookContext): Promise<void> {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts` (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.triggerHooks.call(hooksAndFunctionsHost.of(this), event, context);
}
private hasHooksFor(event: string, object: string): boolean {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts`, its docblock with it (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.hasHooksFor.call(hooksAndFunctionsHost.of(this), event, object);
}
private opensAfterAbortUnit(event: 'afterInsert' | 'afterUpdate' | 'afterDelete', object: string, context: ExecutionContext | undefined): boolean {
// [#29986 codemod] The body moved to `engine-hooks-and-functions.ts`, its docblock with it (see `HooksAndFunctionsHost`).
return HooksAndFunctionsFacet.opensAfterAbortUnit.call(hooksAndFunctionsHost.of(this), event, object, context);
}
private async inAfterAbortUnit<T>(write: () => Promise<T>): Promise<T> {
// [#25522 cut 6] The body moved to `engine-hook-dispatch.ts`, its docblock with it (see `HookDispatchHost`).
const host: ThisParameterType<typeof inAfterAbortUnit> = {
transaction: (...a) => this.transaction(...a),
};
return (inAfterAbortUnit<T>).call(host, write);
}
private buildPerRowAfterContexts(
object: string,
event: 'afterUpdate' | 'afterDelete',
rows: Record<string, unknown>[],
batchCtx: HookContext,
payload?: Record<string, unknown>,
): HookContext[] {
// [#25522 cut 6] The body moved to `engine-hook-dispatch.ts`, its docblock with it (see `HookDispatchHost`).
const readRegistry = () => this._registry;
const host: ThisParameterType<typeof buildPerRowAfterContexts> = {
get _registry() { return readRegistry(); },
};
return buildPerRowAfterContexts.call(host, object, event, rows, batchCtx, payload);
}
private async dispatchPerRowBeforeHooks(
object: string,
event: 'beforeUpdate' | 'beforeDelete',
rows: Record<string, unknown>[],
batchCtx: HookContext,
): Promise<void> {
// [#25522 cut 6] The body moved to `engine-hook-dispatch.ts`, its docblock with it (see `HookDispatchHost`).
const readRegistry = () => this._registry;
const host: ThisParameterType<typeof dispatchPerRowBeforeHooks> = {
get _registry() { return readRegistry(); },
triggerHooks: (...a) => this.triggerHooks(...a),
};
return dispatchPerRowBeforeHooks.call(host, object, event, rows, batchCtx);
}