@deepseek-ai/dsh-typert-registry 0.2.2-alpha.3 → 0.2.2-rc.2

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/src/service.ts ADDED
@@ -0,0 +1,817 @@
1
+ /**
2
+ * Runtime registry for generated Typert reflection, Remote invocations, and
3
+ * dependency-inverted lookup/Context providers. It performs no TypeScript
4
+ * analysis or schema generation.
5
+ * @module @deepseek-ai/dsh-typert-registry
6
+ */
7
+
8
+ import { Context, Service } from '@deepseek-ai/cordis'
9
+ import { z } from 'zod'
10
+ import type {
11
+ InvocationDescriptor,
12
+ RemoteAccessResourceKind,
13
+ TypertClientContextAdapter,
14
+ TypertContextMap,
15
+ TypertContextRegistry,
16
+ TypertContextWire,
17
+ TypertDisposer,
18
+ TypertHostContextAdapter,
19
+ TypertHostContextResolver,
20
+ TypertResourceDeclaration,
21
+ TypertResourceRegistry,
22
+ TypertLocalRegistry,
23
+ TypertLookupHost,
24
+ TypertLookupDefinition,
25
+ TypertLookupMap,
26
+ TypertLookupProvider,
27
+ TypertLookupResolver,
28
+ TypertLookupRegistry,
29
+ TypertLookupWire,
30
+ TypertRemoteContribution,
31
+ TypertRemoteRegistry,
32
+ TypertRegistryChange,
33
+ TypertRegistryListener,
34
+ TypertRegistryContract,
35
+ } from '@deepseek-ai/dsh-typert-protocol'
36
+ import type {
37
+ TypertContribution,
38
+ TypertFace,
39
+ TypertPackageFilter,
40
+ TypertPackageRecord,
41
+ TypertSchemaFactory,
42
+ TypertSchemaFilter,
43
+ TypertSchemaRecord,
44
+ } from './types.ts'
45
+
46
+ /**
47
+ * Compose the global key of one generated schema.
48
+ * @param packageName - contributing npm package.
49
+ * @param name - schema export name.
50
+ * @returns `<package>#<name>`.
51
+ */
52
+ export function typertKey(packageName: string, name: string): string {
53
+ return `${packageName}#${name}`
54
+ }
55
+
56
+ /**
57
+ * Compose the identity of one package-face model.
58
+ * @param packageName - contributing npm package.
59
+ * @param face - independently compiled face.
60
+ * @returns `<package>#<face>`.
61
+ */
62
+ export function typertPackageKey(packageName: string, face: TypertFace): string {
63
+ return `${packageName}#${face}`
64
+ }
65
+
66
+ /**
67
+ * Compose the endpoint key used by local and Remote invocation registries.
68
+ * @param descriptor - invocation whose namespace and method form the endpoint.
69
+ * @returns `<namespace>/<method>`.
70
+ */
71
+ export function typertEndpoint(descriptor: Pick<InvocationDescriptor, 'namespace' | 'method'>): string {
72
+ return `${descriptor.namespace}/${descriptor.method}`
73
+ }
74
+
75
+ interface DescriptorEntry {
76
+ readonly descriptor: InvocationDescriptor
77
+ readonly owner: object
78
+ }
79
+
80
+ interface ProviderEntry<Provider> {
81
+ readonly provider: Provider
82
+ readonly owner: object
83
+ }
84
+
85
+ type ReportObserverError = (change: TypertRegistryChange, error: unknown) => void
86
+
87
+ class ChangeSource {
88
+ private readonly listeners = new Set<TypertRegistryListener>()
89
+
90
+ constructor(private readonly report: ReportObserverError) {}
91
+
92
+ subscribe(ctx: Context, listener: TypertRegistryListener): TypertDisposer {
93
+ const { listeners } = this
94
+ return ctx.effect(function* () {
95
+ listeners.add(listener)
96
+ yield () => { listeners.delete(listener) }
97
+ }, 'typert registry subscription')
98
+ }
99
+
100
+ emit(change: TypertRegistryChange): void {
101
+ for (const listener of [...this.listeners]) {
102
+ try {
103
+ listener(change)
104
+ } catch (error) {
105
+ this.report(change, error)
106
+ }
107
+ }
108
+ }
109
+ }
110
+
111
+ class DescriptorStore {
112
+ private readonly entries = new Map<string, DescriptorEntry>()
113
+ private readonly ids = new Map<string, DescriptorEntry>()
114
+ private readonly history = new Set<string>()
115
+ private readonly changes: ChangeSource
116
+
117
+ constructor(
118
+ private readonly kind: 'local' | 'remote',
119
+ report: ReportObserverError,
120
+ ) {
121
+ this.changes = new ChangeSource(report)
122
+ }
123
+
124
+ validate(descriptors: readonly InvocationDescriptor[]): void {
125
+ const endpoints = new Set<string>()
126
+ const ids = new Set<string>()
127
+ for (const descriptor of descriptors) {
128
+ validateInvocation(descriptor)
129
+ const endpoint = typertEndpoint(descriptor)
130
+ if (endpoints.has(endpoint) || this.entries.has(endpoint)) {
131
+ throw new Error(`typert: ${this.kind} endpoint "${endpoint}" is already registered`)
132
+ }
133
+ if (ids.has(descriptor.id) || this.ids.has(descriptor.id)) {
134
+ throw new Error(`typert: ${this.kind} invocation id "${descriptor.id}" is already registered`)
135
+ }
136
+ endpoints.add(endpoint)
137
+ ids.add(descriptor.id)
138
+ }
139
+ }
140
+
141
+ commit(owner: object, descriptors: readonly InvocationDescriptor[]): void {
142
+ for (const descriptor of descriptors) {
143
+ const entry = { descriptor, owner }
144
+ const endpoint = typertEndpoint(descriptor)
145
+ this.entries.set(endpoint, entry)
146
+ this.ids.set(descriptor.id, entry)
147
+ this.history.add(endpoint)
148
+ }
149
+ for (const descriptor of descriptors) {
150
+ this.changes.emit({ kind: this.kind, key: typertEndpoint(descriptor) })
151
+ }
152
+ }
153
+
154
+ withdraw(owner: object, descriptors: readonly InvocationDescriptor[]): void {
155
+ const removed: string[] = []
156
+ for (const descriptor of descriptors) {
157
+ const endpoint = typertEndpoint(descriptor)
158
+ const entry = this.entries.get(endpoint)
159
+ /* v8 ignore next -- duplicate registration is rejected, so no later owner can replace this entry before its effect disposes. */
160
+ if (entry?.owner !== owner) continue
161
+ this.entries.delete(endpoint)
162
+ /* v8 ignore next -- ids and endpoints are committed and withdrawn together under the same unique owner. */
163
+ if (this.ids.get(descriptor.id) === entry) this.ids.delete(descriptor.id)
164
+ removed.push(endpoint)
165
+ }
166
+ for (const endpoint of removed) this.changes.emit({ kind: this.kind, key: endpoint })
167
+ }
168
+
169
+ get(endpoint: string): InvocationDescriptor | undefined {
170
+ return this.entries.get(endpoint)?.descriptor
171
+ }
172
+
173
+ hasSeen(endpoint: string): boolean {
174
+ return this.history.has(endpoint)
175
+ }
176
+
177
+ list(): readonly InvocationDescriptor[] {
178
+ return [...this.entries.values()].map(entry => entry.descriptor)
179
+ }
180
+
181
+ subscribe(ctx: Context, listener: TypertRegistryListener): TypertDisposer {
182
+ return this.changes.subscribe(ctx, listener)
183
+ }
184
+ }
185
+
186
+ class RemoteStore {
187
+ private readonly packages = new Map<string, object>()
188
+
189
+ constructor(private readonly descriptors: DescriptorStore) {}
190
+
191
+ view(ctx: Context): TypertRemoteRegistry {
192
+ return {
193
+ register: contribution => this.register(ctx, contribution),
194
+ get: endpoint => this.descriptors.get(endpoint),
195
+ list: () => this.descriptors.list(),
196
+ subscribe: listener => this.descriptors.subscribe(ctx, listener),
197
+ }
198
+ }
199
+
200
+ private register(ctx: Context, contribution: TypertRemoteContribution): TypertDisposer {
201
+ validateSegment('Remote package name', contribution.package)
202
+ if (this.packages.has(contribution.package)) {
203
+ throw new Error(`typert: Remote package "${contribution.package}" is already registered`)
204
+ }
205
+ this.descriptors.validate(contribution.descriptors)
206
+ const owner = {}
207
+ const { packages, descriptors } = this
208
+ return ctx.effect(function* () {
209
+ packages.set(contribution.package, owner)
210
+ descriptors.commit(owner, contribution.descriptors)
211
+ yield () => {
212
+ /* v8 ignore else -- duplicate package registration is rejected, so this effect remains the package's unique owner. */
213
+ if (packages.get(contribution.package) === owner) packages.delete(contribution.package)
214
+ descriptors.withdraw(owner, contribution.descriptors)
215
+ }
216
+ }, `typert.remotes.register(${JSON.stringify(contribution.package)})`)
217
+ }
218
+ }
219
+
220
+ class LookupStore {
221
+ private readonly providers = new Map<string, ProviderEntry<TypertLookupProvider>>()
222
+ private readonly resolvers = new Map<string, ProviderEntry<LookupResolverEntry>>()
223
+ private readonly definitions = new Map<string, TypertLookupDefinition>()
224
+ private readonly changes: ChangeSource
225
+
226
+ constructor(report: ReportObserverError) {
227
+ this.changes = new ChangeSource(report)
228
+ }
229
+
230
+ view(ctx: Context): TypertLookupRegistry {
231
+ return {
232
+ register: <K extends Extract<keyof TypertLookupMap, string>>(
233
+ key: K,
234
+ provider: TypertLookupProvider<
235
+ TypertLookupHost<TypertLookupMap[K]>,
236
+ TypertLookupWire<TypertLookupMap[K]>
237
+ >,
238
+ ) => this.register(ctx, key, provider),
239
+ configure: <K extends Extract<keyof TypertLookupMap, string>>(
240
+ key: K,
241
+ resolver: TypertLookupResolver<
242
+ TypertLookupHost<TypertLookupMap[K]>,
243
+ TypertLookupWire<TypertLookupMap[K]>
244
+ >,
245
+ ) => this.configure(ctx, key, resolver),
246
+ get: key => this.get(key),
247
+ definitions: () => [...this.definitions.values()],
248
+ keys: () => [...this.providers.keys()],
249
+ subscribe: listener => this.changes.subscribe(ctx, listener),
250
+ }
251
+ }
252
+
253
+ private get(key: string): TypertLookupProvider | undefined {
254
+ const provider = this.providers.get(key)?.provider
255
+ if (provider === undefined) return undefined
256
+ const resolver = this.resolvers.get(key)?.provider
257
+ if (resolver === undefined) return provider
258
+ return {
259
+ parameter: provider.parameter,
260
+ wire: provider.wire,
261
+ // oxlint-disable-next-line typescript/no-unnecessary-condition -- domain packages merge resource kinds into TypertResourceMap.
262
+ ...provider.resource === undefined ? {} : { resource: provider.resource },
263
+ hostTypeSymbol: provider.hostTypeSymbol,
264
+ wireTypeSymbol: provider.wireTypeSymbol,
265
+ resolve: id => resolver.resolve(id),
266
+ }
267
+ }
268
+
269
+ private configure<Host, Wire>(
270
+ ctx: Context,
271
+ key: string,
272
+ resolver: TypertLookupResolver<Host, Wire>,
273
+ ): TypertDisposer {
274
+ validateSegment('lookup key', key)
275
+ if (this.resolvers.has(key)) throw new Error(`typert: lookup "${key}" resolver is already configured`)
276
+ const owner = {}
277
+ // The map erases each merge-declared Wire type; restore it only at the
278
+ // typed configure() boundary so strict function variance remains sound.
279
+ const entry: ProviderEntry<LookupResolverEntry> = {
280
+ provider: { resolve: async id => resolver(id as Wire) },
281
+ owner,
282
+ }
283
+ const { resolvers, changes } = this
284
+ return ctx.effect(function* () {
285
+ resolvers.set(key, entry)
286
+ changes.emit({ kind: 'lookup', key })
287
+ yield () => {
288
+ /* v8 ignore next -- duplicate configuration is rejected, so this effect remains the key's unique owner. */
289
+ if (resolvers.get(key) !== entry) return
290
+ resolvers.delete(key)
291
+ changes.emit({ kind: 'lookup', key })
292
+ }
293
+ }, `typert.lookups.configure(${JSON.stringify(key)})`)
294
+ }
295
+
296
+ private register<Host, Wire>(ctx: Context, key: string, provider: TypertLookupProvider<Host, Wire>): TypertDisposer {
297
+ validateSegment('lookup key', key)
298
+ validateSegment('lookup parameter', provider.parameter)
299
+ validateWireName('lookup wire field', provider.wire)
300
+ validateNonempty('lookup Host type symbol', provider.hostTypeSymbol)
301
+ validateNonempty('lookup wire type symbol', provider.wireTypeSymbol)
302
+ if (this.providers.has(key)) throw new Error(`typert: lookup "${key}" is already registered`)
303
+ const definition: TypertLookupDefinition = {
304
+ key,
305
+ parameter: provider.parameter,
306
+ wire: provider.wire,
307
+ hostTypeSymbol: provider.hostTypeSymbol,
308
+ wireTypeSymbol: provider.wireTypeSymbol,
309
+ }
310
+ const known = this.definitions.get(key)
311
+ if (known !== undefined && !lookupDefinitionEquals(known, definition)) {
312
+ throw new Error(`typert: lookup "${key}" changed its wire declaration during this registry lifetime`)
313
+ }
314
+ const owner = {}
315
+ const entry: ProviderEntry<TypertLookupProvider> = { provider, owner }
316
+ const { definitions, providers, changes } = this
317
+ return ctx.effect(function* () {
318
+ definitions.set(key, definition)
319
+ providers.set(key, entry)
320
+ changes.emit({ kind: 'lookup', key })
321
+ yield () => {
322
+ /* v8 ignore next -- duplicate registration is rejected, so this effect remains the key's unique owner. */
323
+ if (providers.get(key) !== entry) return
324
+ providers.delete(key)
325
+ changes.emit({ kind: 'lookup', key })
326
+ }
327
+ }, `typert.lookups.register(${JSON.stringify(key)})`)
328
+ }
329
+ }
330
+
331
+ interface LookupResolverEntry {
332
+ resolve(id: unknown): Promise<unknown>
333
+ }
334
+
335
+ function lookupDefinitionEquals(left: TypertLookupDefinition, right: TypertLookupDefinition): boolean {
336
+ return left.parameter === right.parameter
337
+ && left.wire === right.wire
338
+ && left.hostTypeSymbol === right.hostTypeSymbol
339
+ && left.wireTypeSymbol === right.wireTypeSymbol
340
+ }
341
+
342
+ class ContextStore {
343
+ private readonly hosts = new Map<string, ProviderEntry<TypertHostContextAdapter>>()
344
+ private readonly hostResolvers = new Map<string, ProviderEntry<HostContextResolverEntry>>()
345
+ private readonly clients = new Map<string, ProviderEntry<TypertClientContextAdapter>>()
346
+ private readonly changes: ChangeSource
347
+
348
+ constructor(report: ReportObserverError) {
349
+ this.changes = new ChangeSource(report)
350
+ }
351
+
352
+ view(ctx: Context): TypertContextRegistry {
353
+ return {
354
+ registerHost: <K extends Extract<keyof TypertContextMap, string>>(
355
+ key: K,
356
+ adapter: TypertHostContextAdapter<TypertContextWire<TypertContextMap[K]>>,
357
+ ) => this.registerHost(ctx, key, adapter),
358
+ configureHost: <K extends Extract<keyof TypertContextMap, string>>(
359
+ key: K,
360
+ resolver: TypertHostContextResolver<TypertContextWire<TypertContextMap[K]>>,
361
+ ) => this.configureHost(ctx, key, resolver),
362
+ registerClient: <K extends Extract<keyof TypertContextMap, string>>(
363
+ key: K,
364
+ adapter: TypertClientContextAdapter<TypertContextWire<TypertContextMap[K]>>,
365
+ ) => this.registerClient(ctx, key, adapter),
366
+ getHost: key => this.getHost(key),
367
+ getClient: key => this.clients.get(key)?.provider,
368
+ subscribe: listener => this.changes.subscribe(ctx, listener),
369
+ }
370
+ }
371
+
372
+ private getHost(key: string): TypertHostContextAdapter | undefined {
373
+ const adapter = this.hosts.get(key)?.provider
374
+ if (adapter === undefined) return undefined
375
+ const resolver = this.hostResolvers.get(key)?.provider
376
+ if (resolver === undefined) return adapter
377
+ return {
378
+ wire: adapter.wire,
379
+ wireTypeSymbol: adapter.wireTypeSymbol,
380
+ // oxlint-disable-next-line typescript/no-unnecessary-condition -- domain packages merge resource kinds into TypertResourceMap.
381
+ ...adapter.resource === undefined ? {} : { resource: adapter.resource },
382
+ resolve: id => resolver.resolve(id),
383
+ }
384
+ }
385
+
386
+ private configureHost<Wire>(
387
+ ctx: Context,
388
+ key: string,
389
+ resolver: TypertHostContextResolver<Wire>,
390
+ ): TypertDisposer {
391
+ validateSegment('Context key', key)
392
+ if (this.hostResolvers.has(key)) throw new Error(`typert: host-context "${key}" resolver is already configured`)
393
+ const entry: ProviderEntry<HostContextResolverEntry> = {
394
+ provider: { resolve: async id => resolver(id as Wire) },
395
+ owner: {},
396
+ }
397
+ const { hostResolvers, changes } = this
398
+ return ctx.effect(function* () {
399
+ hostResolvers.set(key, entry)
400
+ changes.emit({ kind: 'host-context', key })
401
+ yield () => {
402
+ /* v8 ignore next -- duplicate configuration is rejected, so this effect remains the key's unique owner. */
403
+ if (hostResolvers.get(key) !== entry) return
404
+ hostResolvers.delete(key)
405
+ changes.emit({ kind: 'host-context', key })
406
+ }
407
+ }, `typert.contexts.configureHost(${JSON.stringify(key)})`)
408
+ }
409
+
410
+ private registerHost<Wire>(ctx: Context, key: string, adapter: TypertHostContextAdapter<Wire>): TypertDisposer {
411
+ validateSegment('Context key', key)
412
+ validateWireName('Context wire field', adapter.wire)
413
+ validateNonempty('Context wire type symbol', adapter.wireTypeSymbol)
414
+ return this.registerProvider(ctx, this.hosts, 'host-context', key, adapter)
415
+ }
416
+
417
+ private registerClient<Wire>(ctx: Context, key: string, adapter: TypertClientContextAdapter<Wire>): TypertDisposer {
418
+ validateSegment('Context key', key)
419
+ return this.registerProvider(ctx, this.clients, 'client-context', key, adapter)
420
+ }
421
+
422
+ private registerProvider<Provider>(
423
+ ctx: Context,
424
+ table: Map<string, ProviderEntry<Provider>>,
425
+ kind: 'host-context' | 'client-context',
426
+ key: string,
427
+ provider: Provider,
428
+ ): TypertDisposer {
429
+ if (table.has(key)) throw new Error(`typert: ${kind} provider "${key}" is already registered`)
430
+ const entry: ProviderEntry<Provider> = { provider, owner: {} }
431
+ const { changes } = this
432
+ return ctx.effect(function* () {
433
+ table.set(key, entry)
434
+ changes.emit({ kind, key })
435
+ yield () => {
436
+ /* v8 ignore next -- duplicate registration is rejected, so this effect remains the key's unique owner. */
437
+ if (table.get(key) !== entry) return
438
+ table.delete(key)
439
+ changes.emit({ kind, key })
440
+ }
441
+ }, `typert.contexts.register(${JSON.stringify(key)})`)
442
+ }
443
+ }
444
+
445
+ interface HostContextResolverEntry {
446
+ resolve(id: unknown): Promise<Context | undefined>
447
+ }
448
+
449
+ /** The built-in identity-less resource kind; no declared resource kind may take its name. */
450
+ const GLOBAL_RESOURCE_KIND = 'global' satisfies RemoteAccessResourceKind
451
+
452
+ class ResourceStore {
453
+ private readonly declarations = new Map<string, ProviderEntry<TypertResourceDeclaration>>()
454
+ private readonly changes: ChangeSource
455
+
456
+ constructor(report: ReportObserverError) {
457
+ this.changes = new ChangeSource(report)
458
+ }
459
+
460
+ view(ctx: Context): TypertResourceRegistry {
461
+ return {
462
+ register: (kind, declaration) => this.register(ctx, kind, declaration),
463
+ get: kind => this.declarations.get(kind)?.provider,
464
+ entries: () => [...this.declarations].map(([kind, entry]) => Object.freeze({ kind, ...entry.provider })),
465
+ subscribe: listener => this.changes.subscribe(ctx, listener),
466
+ }
467
+ }
468
+
469
+ private register(ctx: Context, kind: string, declaration: TypertResourceDeclaration): TypertDisposer {
470
+ validateSegment('resource kind', kind)
471
+ if (kind === GLOBAL_RESOURCE_KIND) {
472
+ throw new Error(`typert: resource kind "${GLOBAL_RESOURCE_KIND}" is reserved for the built-in global resource`)
473
+ }
474
+ if (this.declarations.has(kind)) throw new Error(`typert: resource kind "${kind}" is already registered`)
475
+ // Copy by branch so a prototype method cannot vanish in a spread; an opaque declaration fails here
476
+ // rather than resolving every call of this kind to the global resource.
477
+ const resolve = declaration.resolve
478
+ const field = declaration.field
479
+ let provider: TypertResourceDeclaration
480
+ if (resolve !== undefined) {
481
+ provider = { resolve }
482
+ } else if (field !== undefined) {
483
+ validateWireName('resource field', field)
484
+ provider = { field }
485
+ } else {
486
+ throw new Error(`typert: resource kind "${kind}" declares neither a field nor a resolve function`)
487
+ }
488
+ const entry: ProviderEntry<TypertResourceDeclaration> = { provider, owner: {} }
489
+ const { declarations, changes } = this
490
+ return ctx.effect(function* () {
491
+ declarations.set(kind, entry)
492
+ changes.emit({ kind: 'resource', key: kind })
493
+ yield () => {
494
+ /* v8 ignore next -- duplicate registration is rejected, so this effect remains the kind's unique owner. */
495
+ if (declarations.get(kind) !== entry) return
496
+ declarations.delete(kind)
497
+ changes.emit({ kind: 'resource', key: kind })
498
+ }
499
+ }, `typert.resources.register(${JSON.stringify(kind)})`)
500
+ }
501
+ }
502
+
503
+ /**
504
+ * Registry of generated schemas, package reflection, invocations, and Remote
505
+ * dependency providers.
506
+ * @typert service typert
507
+ */
508
+ export class TypertRegistry extends Service implements TypertRegistryContract {
509
+ private readonly schemas = new Map<string, TypertSchemaFactoryRecord>()
510
+ private readonly packages = new Map<string, TypertPackageRecord>()
511
+ private readonly localStore: DescriptorStore
512
+ private readonly remoteStore: RemoteStore
513
+ private readonly lookupStore: LookupStore
514
+ private readonly contextStore: ContextStore
515
+ private readonly resourceStore: ResourceStore
516
+
517
+ constructor(ctx: Context) {
518
+ super(ctx, 'typert')
519
+ const report: ReportObserverError = (change, error) => {
520
+ ctx.logger.warn(`typert: ${change.kind} observer for "${change.key}" failed`)
521
+ ctx.logger.warn(error)
522
+ }
523
+ this.localStore = new DescriptorStore('local', report)
524
+ this.remoteStore = new RemoteStore(new DescriptorStore('remote', report))
525
+ this.lookupStore = new LookupStore(report)
526
+ this.contextStore = new ContextStore(report)
527
+ this.resourceStore = new ResourceStore(report)
528
+ }
529
+
530
+ /** Current-environment invocation definitions. */
531
+ get local(): TypertLocalRegistry {
532
+ const ctx = this.ctx
533
+ return {
534
+ get: endpoint => this.localStore.get(endpoint),
535
+ hasSeen: endpoint => this.localStore.hasSeen(endpoint),
536
+ list: () => this.localStore.list(),
537
+ subscribe: listener => this.localStore.subscribe(ctx, listener),
538
+ }
539
+ }
540
+
541
+ /** Consumer-selected Remote definitions. */
542
+ get remotes(): TypertRemoteRegistry {
543
+ return this.remoteStore.view(this.ctx)
544
+ }
545
+
546
+ /** Host object lookup providers. */
547
+ get lookups(): TypertLookupRegistry {
548
+ return this.lookupStore.view(this.ctx)
549
+ }
550
+
551
+ /** Host and Client Context adapters. */
552
+ get contexts(): TypertContextRegistry {
553
+ return this.contextStore.view(this.ctx)
554
+ }
555
+
556
+ /** Default wire fields of resource kinds. */
557
+ get resources(): TypertResourceRegistry {
558
+ return this.resourceStore.view(this.ctx)
559
+ }
560
+
561
+ /**
562
+ * Register one generated contribution atomically for the calling fiber.
563
+ * Duplicate package-face identities, schemas, invocation ids, or endpoints
564
+ * reject the whole batch.
565
+ * @param contribution - generated schemas, reflection, and Host invocations.
566
+ * @returns the exact effect disposer that removes this contribution.
567
+ */
568
+ register(contribution: TypertContribution): TypertDisposer {
569
+ const packageRecord = this.validatePackage(contribution)
570
+ const schemaRecords = this.validateSchemas(contribution)
571
+ const invocations = contribution.invocations
572
+ this.localStore.validate(invocations)
573
+ const owner = {}
574
+ const { schemas, packages, localStore } = this
575
+ return this.ctx.effect(function* () {
576
+ packages.set(packageRecord.key, packageRecord)
577
+ for (const record of schemaRecords) schemas.set(record.key, record)
578
+ localStore.commit(owner, invocations)
579
+ yield () => {
580
+ /* v8 ignore else -- duplicate package-face registration is rejected, so this effect remains its unique owner. */
581
+ if (packages.get(packageRecord.key) === packageRecord) packages.delete(packageRecord.key)
582
+ for (const record of schemaRecords) {
583
+ /* v8 ignore else -- duplicate schema registration is rejected, so this contribution remains each record's unique owner. */
584
+ if (schemas.get(record.key) === record) schemas.delete(record.key)
585
+ }
586
+ localStore.withdraw(owner, invocations)
587
+ }
588
+ }, 'typert.register()')
589
+ }
590
+
591
+ /**
592
+ * Look up one schema by `<package>#<name>`.
593
+ * @param key - global schema key.
594
+ * @returns a record containing the cached schema, or `undefined` when absent.
595
+ */
596
+ get(key: string): TypertSchemaRecord | undefined {
597
+ const record = this.schemas.get(key)
598
+ return record === undefined ? undefined : materializeSchema(record)
599
+ }
600
+
601
+ /**
602
+ * Resolve one required schema.
603
+ * @param key - global schema key.
604
+ * @returns a record containing the cached schema.
605
+ * @throws when the key is malformed, the package face is absent, or the schema is not contributed.
606
+ */
607
+ resolve(key: string): TypertSchemaRecord {
608
+ const record = this.schemas.get(key)
609
+ if (record !== undefined) return materializeSchema(record)
610
+ const hash = key.indexOf('#')
611
+ if (hash <= 0 || hash === key.length - 1) {
612
+ throw new Error(`typert: invalid schema key "${key}" — expected "<package>#<name>"`)
613
+ }
614
+ const packageName = key.slice(0, hash)
615
+ if ([...this.packages.values()].some(candidate => candidate.package === packageName)) {
616
+ throw new Error(
617
+ `typert: cannot resolve "${key}" — package "${packageName}" is registered but contributes no schema named "${key.slice(hash + 1)}"`,
618
+ )
619
+ }
620
+ throw new Error(`typert: cannot resolve "${key}" — package "${packageName}" has no registered contribution`)
621
+ }
622
+
623
+ /**
624
+ * Enumerate live schemas in registration order.
625
+ * @param filter - optional package and face restriction.
626
+ * @returns matching records containing the cached schemas.
627
+ */
628
+ list(filter: TypertSchemaFilter = {}): TypertSchemaRecord[] {
629
+ return [...this.schemas.values()].filter(record => matches(record, filter)).map(materializeSchema)
630
+ }
631
+
632
+ /**
633
+ * Look up generated reflection for one package face.
634
+ * @param packageName - exact npm package name.
635
+ * @param face - face to query; defaults to the host runtime.
636
+ * @returns the live package record, or `undefined` when absent.
637
+ */
638
+ getPackage(packageName: string, face: TypertFace = 'host'): TypertPackageRecord | undefined {
639
+ return this.packages.get(typertPackageKey(packageName, face))
640
+ }
641
+
642
+ /**
643
+ * Enumerate generated package reflection in registration order.
644
+ * @param filter - optional package and face restriction.
645
+ * @returns matching package records.
646
+ */
647
+ listPackages(filter: TypertPackageFilter = {}): TypertPackageRecord[] {
648
+ return [...this.packages.values()].filter(record => matches(record, filter))
649
+ }
650
+
651
+ /**
652
+ * Project a live Zod schema to JSON Schema without caching the result.
653
+ * @param key - global schema key.
654
+ * @param params - Zod projection parameters.
655
+ * @returns a fresh JSON Schema document.
656
+ */
657
+ toJSONSchema(key: string, params?: z.core.ToJSONSchemaParams): z.core.JSONSchema.BaseSchema {
658
+ return z.toJSONSchema(this.resolve(key).schema, params)
659
+ }
660
+
661
+ private validatePackage(contribution: TypertContribution): TypertPackageRecord {
662
+ validateSegment('package name', contribution.package)
663
+ const face: unknown = contribution.face
664
+ if (face !== 'host' && face !== 'client') {
665
+ throw new Error(`typert: invalid face ${JSON.stringify(face)} — expected "host" or "client"`)
666
+ }
667
+ const key = typertPackageKey(contribution.package, contribution.face)
668
+ if (this.packages.has(key)) {
669
+ throw new Error(`typert: package face "${key}" is already registered`)
670
+ }
671
+ return {
672
+ package: contribution.package,
673
+ face,
674
+ key,
675
+ model: contribution.model,
676
+ }
677
+ }
678
+
679
+ private validateSchemas(contribution: TypertContribution): TypertSchemaFactoryRecord[] {
680
+ const records: TypertSchemaFactoryRecord[] = []
681
+ const batch = new Set<string>()
682
+ for (const schema of contribution.schemas) {
683
+ validateSegment('schema name', schema.name)
684
+ if (typeof schema.create !== 'function') {
685
+ throw new Error(`typert: schema "${schema.name}" has no create() factory`)
686
+ }
687
+ const key = typertKey(contribution.package, schema.name)
688
+ if (batch.has(key) || this.schemas.has(key)) {
689
+ throw new Error(`typert: schema "${key}" is already registered`)
690
+ }
691
+ batch.add(key)
692
+ records.push({
693
+ ...schema,
694
+ package: contribution.package,
695
+ face: contribution.face,
696
+ key,
697
+ })
698
+ }
699
+ return records
700
+ }
701
+ }
702
+
703
+ interface TypertSchemaFactoryRecord extends TypertSchemaFactory {
704
+ readonly package: string
705
+ readonly face: TypertFace
706
+ readonly key: string
707
+ value?: z.ZodType
708
+ }
709
+
710
+ function materializeSchema(record: TypertSchemaFactoryRecord): TypertSchemaRecord {
711
+ const schema = record.value ??= record.create()
712
+ return {
713
+ name: record.name,
714
+ schema,
715
+ package: record.package,
716
+ face: record.face,
717
+ key: record.key,
718
+ }
719
+ }
720
+
721
+ function matches(
722
+ record: { readonly package: string; readonly face: TypertFace },
723
+ filter: { readonly package?: string; readonly face?: TypertFace },
724
+ ): boolean {
725
+ return (filter.package === undefined || record.package === filter.package)
726
+ && (filter.face === undefined || record.face === filter.face)
727
+ }
728
+
729
+ function validateInvocation(descriptor: InvocationDescriptor): void {
730
+ validateNonempty('invocation id', descriptor.id)
731
+ validateSegment('invocation service key', descriptor.service)
732
+ validateWireName('invocation namespace', descriptor.namespace)
733
+ validateWireName('invocation method', descriptor.method)
734
+ if (descriptor.implementation !== undefined) {
735
+ validateWireName('invocation implementation method', descriptor.implementation)
736
+ }
737
+ validateCodec(descriptor.result, `${descriptor.id} result`)
738
+ const wires = new Set<string>()
739
+ for (const parameter of descriptor.parameters) {
740
+ validateWireName('parameter name', parameter.name)
741
+ validateWireName('parameter wire field', parameter.wire)
742
+ if (wires.has(parameter.wire)) {
743
+ throw new Error(`typert: invocation "${descriptor.id}" repeats wire field "${parameter.wire}"`)
744
+ }
745
+ wires.add(parameter.wire)
746
+ if (parameter.source === 'lookup') {
747
+ if (parameter.acceptsUndefined !== undefined) {
748
+ throw new Error(`typert: invocation "${descriptor.id}" lookup parameter "${parameter.name}" cannot accept undefined`)
749
+ }
750
+ if (parameter.lookup === undefined) {
751
+ throw new Error(`typert: invocation "${descriptor.id}" lookup parameter "${parameter.name}" has no lookup key`)
752
+ }
753
+ validateSegment('lookup key', parameter.lookup)
754
+ } else if (parameter.lookup !== undefined) {
755
+ throw new Error(`typert: invocation "${descriptor.id}" JSON parameter "${parameter.name}" declares a lookup key`)
756
+ }
757
+ validateCodec(parameter.codec, `${descriptor.id} parameter ${parameter.name}`)
758
+ }
759
+ const cancellation = descriptor.cancellation as { readonly parameter: string } | undefined
760
+ if (cancellation !== undefined && cancellation.parameter !== 'signal') {
761
+ throw new Error(`typert: invocation "${descriptor.id}" cancellation parameter must be "signal"`)
762
+ }
763
+ const mode = descriptor.mode as string | undefined
764
+ if (mode !== undefined && mode !== 'stream') {
765
+ throw new Error(`typert: invocation "${descriptor.id}" mode must be "stream"`)
766
+ }
767
+ if (descriptor.uplink !== undefined) validateCodec(descriptor.uplink.codec, `${descriptor.id} uplink`)
768
+ if (descriptor.scope !== undefined) {
769
+ if (descriptor.invocation.kind !== 'direct') {
770
+ throw new Error(`typert: invocation "${descriptor.id}" Context receiver cannot declare a direct scope projection`)
771
+ }
772
+ validateSegment('scope Context key', descriptor.scope.context)
773
+ validateWireName('scope wire field', descriptor.scope.wire)
774
+ const lookups = descriptor.parameters.filter(candidate => candidate.source === 'lookup')
775
+ const parameter = lookups.length === 1 ? lookups[0] : undefined
776
+ if (parameter === undefined || parameter.wire !== descriptor.scope.wire
777
+ || parameter.lookup !== descriptor.scope.context) {
778
+ throw new Error(
779
+ `typert: invocation "${descriptor.id}" scope wire "${descriptor.scope.wire}" must select its only lookup parameter`,
780
+ )
781
+ }
782
+ }
783
+ if (descriptor.invocation.kind === 'context') {
784
+ validateSegment('Context key', descriptor.invocation.context)
785
+ validateWireName('Context wire field', descriptor.invocation.wire)
786
+ if (wires.has(descriptor.invocation.wire)) {
787
+ throw new Error(`typert: invocation "${descriptor.id}" repeats wire field "${descriptor.invocation.wire}"`)
788
+ }
789
+ validateCodec(descriptor.invocation.codec, `${descriptor.id} Context`)
790
+ }
791
+ }
792
+
793
+ function validateCodec(codec: InvocationDescriptor['result'], subject: string): void {
794
+ if (codec.mode === 'src-json') return
795
+ validateNonempty(`${subject} type symbol`, codec.typeSymbol)
796
+ if (typeof codec.create !== 'function') {
797
+ throw new Error(`typert: ${subject} strict codec has no create() factory`)
798
+ }
799
+ }
800
+
801
+ function validateWireName(subject: string, value: string): void {
802
+ if (value === '.' || value === '..' || !/^[A-Za-z0-9_$.-]+$/.test(value)) {
803
+ throw new Error(`typert: invalid ${subject} "${value}" — must contain only RPC endpoint segment characters`)
804
+ }
805
+ }
806
+
807
+ function validateSegment(subject: string, value: string): void {
808
+ if (value.length === 0 || value.includes('#')) {
809
+ throw new Error(`typert: invalid ${subject} "${value}" — must be nonempty and must not contain "#"`)
810
+ }
811
+ }
812
+
813
+ function validateNonempty(subject: string, value: string): void {
814
+ if (value.length === 0) throw new Error(`typert: invalid ${subject} — must be nonempty`)
815
+ }
816
+
817
+ export default TypertRegistry