@spellkave/world-author 0.0.0-bootstrap
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/LICENSE +89 -0
- package/README.md +62 -0
- package/package.json +57 -0
- package/src/applyset-diff-types.ts +158 -0
- package/src/applyset.ts +82 -0
- package/src/authoring-harness.ts +487 -0
- package/src/browser.ts +114 -0
- package/src/compose.ts +699 -0
- package/src/corpus.generated.ts +279 -0
- package/src/corpus.ts +1180 -0
- package/src/damage.ts +75 -0
- package/src/diagnostics.ts +59 -0
- package/src/diff-manifest-core.ts +393 -0
- package/src/diff-manifest.ts +5 -0
- package/src/docs-index.ts +105 -0
- package/src/dsl.ts +10 -0
- package/src/evaluate.ts +100 -0
- package/src/explain-core.ts +219 -0
- package/src/explain.ts +43 -0
- package/src/filter-manifest-core.ts +122 -0
- package/src/filter-manifest.ts +41 -0
- package/src/grants-core.ts +38 -0
- package/src/grants.ts +10 -0
- package/src/included-manifest-metadata-core.ts +63 -0
- package/src/included-manifest-metadata.ts +21 -0
- package/src/index.ts +30 -0
- package/src/inspect.ts +35 -0
- package/src/inspection.ts +239 -0
- package/src/lint.ts +540 -0
- package/src/manifest-text.ts +21 -0
- package/src/manifest.ts +403 -0
- package/src/metadata.ts +137 -0
- package/src/npc-dm-authority-projection.ts +95 -0
- package/src/npc-dm-documents.ts +339 -0
- package/src/npc-dm-presentation.ts +17 -0
- package/src/npc-dm-srd.ts +51 -0
- package/src/npc-dm-types.ts +723 -0
- package/src/npc-kinds.ts +404 -0
- package/src/npc-quests.ts +319 -0
- package/src/observation-tokens.browser.ts +31 -0
- package/src/observation-tokens.ts +27 -0
- package/src/owner-instance-read.ts +765 -0
- package/src/patch.ts +47 -0
- package/src/ref-tags.ts +149 -0
- package/src/reference.ts +48 -0
- package/src/row-identity.ts +105 -0
- package/src/row-kinds-data.ts +35 -0
- package/src/row-kinds.ts +93 -0
- package/src/scenario-guidance.ts +180 -0
- package/src/scoped-instance-read.ts +187 -0
- package/src/service-only-audience.ts +14 -0
- package/src/session-predicates.ts +6 -0
- package/src/spell.ts +119 -0
- package/src/tag-prefix-families.ts +143 -0
- package/src/tooling.browser.ts +397 -0
- package/src/tooling.ts +38 -0
- package/src/validate.ts +255 -0
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// embedded-manifest: {"category": "production_schema_constructor", "rationale": "admitted instance snapshots produce a transient schema envelope for the existing Rust comparable path", "signatures": ["schema_shape"]}
|
|
2
|
+
/** Shared projection over one detached caller-authenticated transaction snapshot. */
|
|
3
|
+
import type {
|
|
4
|
+
OwnerDescribeAnswer,
|
|
5
|
+
OwnerGetAnswer,
|
|
6
|
+
ScopedInstanceRead,
|
|
7
|
+
ScopedReadSource,
|
|
8
|
+
} from "@spellkave/tool-contracts";
|
|
9
|
+
import {
|
|
10
|
+
describeManifestSchema,
|
|
11
|
+
inspectManifest,
|
|
12
|
+
liveManifestRowIdentities,
|
|
13
|
+
manifestRowIdentities,
|
|
14
|
+
} from "@spellkave/world-author/tooling";
|
|
15
|
+
import { INSTANCE_ROW_KINDS } from "./filter-manifest-core";
|
|
16
|
+
import { createInstanceProjector, type OwnerSnapshot } from "./owner-instance-read";
|
|
17
|
+
|
|
18
|
+
export interface ScopedInstanceSnapshot {
|
|
19
|
+
snapshot: OwnerSnapshot;
|
|
20
|
+
source: ScopedReadSource;
|
|
21
|
+
}
|
|
22
|
+
export interface ScopedSnapshotPort {
|
|
23
|
+
read(): Promise<ScopedInstanceSnapshot>;
|
|
24
|
+
close(): void;
|
|
25
|
+
}
|
|
26
|
+
export function createScopedInstanceRead(port: ScopedSnapshotPort): ScopedInstanceRead {
|
|
27
|
+
return {
|
|
28
|
+
async get(input) {
|
|
29
|
+
if (!(INSTANCE_ROW_KINDS as readonly string[]).includes(input.kind)) {
|
|
30
|
+
return {
|
|
31
|
+
ok: false,
|
|
32
|
+
code: "usage",
|
|
33
|
+
message: `kind '${input.kind}' is not read from a world by this tool`,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
const captured = await port.read();
|
|
38
|
+
return answerWithSource(
|
|
39
|
+
createInstanceProjector({
|
|
40
|
+
snapshot: () => captured.snapshot,
|
|
41
|
+
worldTick: () => BigInt(captured.source.tick),
|
|
42
|
+
}).get(input),
|
|
43
|
+
captured.source,
|
|
44
|
+
);
|
|
45
|
+
} catch {
|
|
46
|
+
return {
|
|
47
|
+
ok: false,
|
|
48
|
+
code: "reader_unavailable",
|
|
49
|
+
message: "caller-scoped instance reader unavailable",
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
async describe(input) {
|
|
54
|
+
if (input.kind !== "entities")
|
|
55
|
+
return {
|
|
56
|
+
ok: false,
|
|
57
|
+
code: "usage",
|
|
58
|
+
message: "describe is defined for entities; use sk get",
|
|
59
|
+
};
|
|
60
|
+
try {
|
|
61
|
+
const captured = await port.read();
|
|
62
|
+
const answer = answerWithSource(
|
|
63
|
+
createInstanceProjector({
|
|
64
|
+
snapshot: () => captured.snapshot,
|
|
65
|
+
worldTick: () => BigInt(captured.source.tick),
|
|
66
|
+
}).describe(input),
|
|
67
|
+
captured.source,
|
|
68
|
+
);
|
|
69
|
+
if (
|
|
70
|
+
answer.ok &&
|
|
71
|
+
["entities", "entity_containment"].some(
|
|
72
|
+
(kind) => captured.source.coverage[kind] !== "complete",
|
|
73
|
+
)
|
|
74
|
+
) {
|
|
75
|
+
answer.chain_end = { reason: "outside_read_scope" };
|
|
76
|
+
}
|
|
77
|
+
return answer;
|
|
78
|
+
} catch {
|
|
79
|
+
return {
|
|
80
|
+
ok: false,
|
|
81
|
+
code: "reader_unavailable",
|
|
82
|
+
message: "caller-scoped instance reader unavailable",
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function answerWithSource<T extends OwnerGetAnswer | OwnerDescribeAnswer>(
|
|
89
|
+
answer: T,
|
|
90
|
+
source: ScopedReadSource,
|
|
91
|
+
): T {
|
|
92
|
+
if (!answer.ok) {
|
|
93
|
+
if (answer.code === "unknown_key")
|
|
94
|
+
return {
|
|
95
|
+
...answer,
|
|
96
|
+
source,
|
|
97
|
+
code: "not_found_in_scope",
|
|
98
|
+
message: "not found in admitted read scope",
|
|
99
|
+
};
|
|
100
|
+
return { ...answer, source };
|
|
101
|
+
}
|
|
102
|
+
return { ...answer, source };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Convert display rows to schema fields; identities/hashes remain Rust-owned. */
|
|
106
|
+
export function scopedComparableManifest(captured: ScopedInstanceSnapshot, bundle: string): string {
|
|
107
|
+
const schema = describeManifestSchema() as {
|
|
108
|
+
properties: Record<string, { items?: { $ref?: string } }>;
|
|
109
|
+
definitions: Record<string, { properties?: Record<string, unknown> }>;
|
|
110
|
+
};
|
|
111
|
+
const projector = createInstanceProjector({
|
|
112
|
+
snapshot: () => captured.snapshot,
|
|
113
|
+
worldTick: () => BigInt(captured.source.tick),
|
|
114
|
+
});
|
|
115
|
+
const manifest = ['"schema_version":"1.0.0"'];
|
|
116
|
+
for (const kind of INSTANCE_ROW_KINDS) {
|
|
117
|
+
if (captured.source.coverage[kind] !== "complete") continue;
|
|
118
|
+
const ref = schema.properties[kind]?.items?.$ref?.split("/").at(-1);
|
|
119
|
+
const fields = ref ? schema.definitions[ref]?.properties : undefined;
|
|
120
|
+
if (!fields) throw new Error(`no comparable schema for ${kind}`);
|
|
121
|
+
const answer = projector.get({ kind, bundle, limit: 10_000, fields: Object.keys(fields) });
|
|
122
|
+
if (!answer.ok) throw new Error(`scoped comparison projection unavailable: ${kind}`);
|
|
123
|
+
const rows = (answer.rows ?? []).map((row) => {
|
|
124
|
+
const entries = Object.entries(row).filter(
|
|
125
|
+
([field, value]) => field in fields && value !== undefined,
|
|
126
|
+
);
|
|
127
|
+
return `{${entries
|
|
128
|
+
.map(([field, value]) => {
|
|
129
|
+
const property = fields[field] as { type?: string | string[] };
|
|
130
|
+
const integer = property.type === "integer" || property.type?.includes("integer");
|
|
131
|
+
// Display rows preserve i64/u64 as decimal strings. Emit their JSON
|
|
132
|
+
// number token directly, avoiding a lossy JavaScript Number roundtrip.
|
|
133
|
+
// Rust still validates the typed field and owns comparable hashing.
|
|
134
|
+
if (integer && (typeof value === "string" || typeof value === "bigint")) {
|
|
135
|
+
if (typeof value === "string" && !/^-?\d+$/.test(value))
|
|
136
|
+
throw new Error(`invalid integer field ${field}`);
|
|
137
|
+
return `${JSON.stringify(field)}:${BigInt(value).toString()}`;
|
|
138
|
+
}
|
|
139
|
+
return `${JSON.stringify(field)}:${JSON.stringify(value)}`;
|
|
140
|
+
})
|
|
141
|
+
.join(",")}}`;
|
|
142
|
+
});
|
|
143
|
+
manifest.push(`${JSON.stringify(kind)}:[${rows.join(",")}]`);
|
|
144
|
+
}
|
|
145
|
+
return `{${manifest.join(",")}}`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Use Rust's storage-key catalog, including composite JSON keys, for admission checks. */
|
|
149
|
+
export function scopedComparableIdentities(captured: ScopedInstanceSnapshot, bundle: string) {
|
|
150
|
+
return liveManifestRowIdentities(scopedComparableManifest(captured, bundle)).rows;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Inline writes have no applyset baseline. Permit only proven new supported rows;
|
|
154
|
+
* replacements/retractions must use the baseline-aware applyset workflow. */
|
|
155
|
+
export function scopedInlineDeltaPreflight(
|
|
156
|
+
toml: string,
|
|
157
|
+
captured?: ScopedInstanceSnapshot,
|
|
158
|
+
): string | undefined {
|
|
159
|
+
const manifest = inspectManifest(toml).manifest as Record<string, unknown>;
|
|
160
|
+
const ids = manifestRowIdentities(toml, true);
|
|
161
|
+
const retractions = (manifest.retractions ?? []) as Array<{ row_kind: string }>;
|
|
162
|
+
const ordinary = ids.rows.filter((row) => row.kind !== "role_bindings");
|
|
163
|
+
if (retractions.some((row) => row.row_kind === "entity")) return "scope_prune_unsupported";
|
|
164
|
+
if (
|
|
165
|
+
ids.untrackable.length ||
|
|
166
|
+
retractions.some((row) => !["role_binding", "role_bindings"].includes(row.row_kind))
|
|
167
|
+
)
|
|
168
|
+
return "unchecked_scoped_write: missing_baseline";
|
|
169
|
+
if (!ordinary.length) return undefined; // separate D-6 binding-only lane
|
|
170
|
+
if (!captured) return "unchecked_scoped_write: reader_unavailable";
|
|
171
|
+
const observations = new Map<string, ReturnType<typeof scopedComparableIdentities>>();
|
|
172
|
+
for (const row of ordinary) {
|
|
173
|
+
const coverage = captured.source.coverage[row.kind] ?? "unsupported_kind";
|
|
174
|
+
if (coverage !== "complete") return `unchecked_scoped_write: ${coverage}`;
|
|
175
|
+
const bundle = row.bundle_id ?? "";
|
|
176
|
+
if (!captured.source.authorized_bundles?.includes(bundle))
|
|
177
|
+
return "unchecked_scoped_write: outside_read_scope";
|
|
178
|
+
let observed = observations.get(bundle);
|
|
179
|
+
if (!observed) {
|
|
180
|
+
observed = scopedComparableIdentities(captured, bundle);
|
|
181
|
+
observations.set(bundle, observed);
|
|
182
|
+
}
|
|
183
|
+
if (observed.some((item) => item.kind === row.kind && item.key === row.key))
|
|
184
|
+
return "unchecked_scoped_write: missing_baseline";
|
|
185
|
+
}
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** crates/spellkave-schema SERVICE_ONLY_AUDIENCE_TAG. A capability whose
|
|
2
|
+
* definition carries it is a metadata audience for service identities only:
|
|
3
|
+
* the server gives a person no document through it
|
|
4
|
+
* (`visible_metadata_attachment`). Every read capability of private NPC
|
|
5
|
+
* configuration carries it. A test reads the Rust constant. */
|
|
6
|
+
export const SERVICE_ONLY_AUDIENCE_TAG = "core.service_only_audience";
|
|
7
|
+
|
|
8
|
+
/** The `capability_definition_tag` marker row for one read capability. */
|
|
9
|
+
export const serviceOnlyAudienceTag = (bundle: string, capability: string) => ({
|
|
10
|
+
bundle_id: bundle,
|
|
11
|
+
capability_id: capability,
|
|
12
|
+
tag: SERVICE_ONLY_AUDIENCE_TAG,
|
|
13
|
+
source: "manifest",
|
|
14
|
+
});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export const PRESENT_GROUPS = 'participant_tag_group_count("faction:")';
|
|
2
|
+
export const STANDING_GROUPS =
|
|
3
|
+
'participant_tag_group_count("faction:", "core/condition/incapacitated")';
|
|
4
|
+
|
|
5
|
+
export const COMBAT_TERMINATION_PREDICATE = `${PRESENT_GROUPS} >= 2 && ${STANDING_GROUPS} <= 1`;
|
|
6
|
+
export const COMBAT_WINNER_PREDICATE = `${STANDING_GROUPS} == 1`;
|
package/src/spell.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// One spell = ONE identity (#835).
|
|
2
|
+
//
|
|
3
|
+
// `emitSpell` builds the IDENTITY/binding rows for a single catalog spell —
|
|
4
|
+
// capability_definition (+tags), the cast action_definition (+tags), and its
|
|
5
|
+
// outcome_template — from ONE declaration, all bound to the SAME catalog id:
|
|
6
|
+
//
|
|
7
|
+
// capability_id == entity_def_id == action_definition.required_capability
|
|
8
|
+
//
|
|
9
|
+
// This is the authoring primitive #835 lever 3 asks for: "add a spell" becomes one
|
|
10
|
+
// declaration, not ~10 hand-wired rows across two delimiters with the catalog entity
|
|
11
|
+
// orphaned. Tags are single-sourced (one list → both the capability and the action,
|
|
12
|
+
// no 3× repetition). The cast ACTION keeps its own verb id (e.g. `srd/cast_fire_bolt`),
|
|
13
|
+
// distinct from the spell IDENTITY — only the identity is unified.
|
|
14
|
+
//
|
|
15
|
+
// Pure row emitter, no filesystem (this package publishes only `src/`, and the
|
|
16
|
+
// validator stays the single source of truth for parsing/type-checking — same posture
|
|
17
|
+
// as `routeDamage` in damage.ts). The catalog-existence check therefore takes the known
|
|
18
|
+
// entity ids as INPUT, so the fs-having caller (an authoring driver) supplies them.
|
|
19
|
+
|
|
20
|
+
const SPELL_CATALOG_PREFIX = "srd/spell/";
|
|
21
|
+
|
|
22
|
+
/** One row table fragment keyed by table name (schema-shaped, ready to render). */
|
|
23
|
+
export interface SpellIdentityRows {
|
|
24
|
+
capability_definitions: Record<string, unknown>[];
|
|
25
|
+
capability_definition_tag: Record<string, unknown>[];
|
|
26
|
+
action_definitions: Record<string, unknown>[];
|
|
27
|
+
action_definition_tag: Record<string, unknown>[];
|
|
28
|
+
outcome_templates: Record<string, unknown>[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface EmitSpellInput {
|
|
32
|
+
/** The single spell identity, `srd/spell/<slug>`. MUST equal the catalog entity_def_id. */
|
|
33
|
+
capabilityId: string;
|
|
34
|
+
/** The cast action verb id (e.g. `srd/cast_fire_bolt`, `srd/bless`) — distinct from the identity. */
|
|
35
|
+
actionId: string;
|
|
36
|
+
bundleId: string;
|
|
37
|
+
displayName: string;
|
|
38
|
+
description?: string;
|
|
39
|
+
/** Single-sourced: applied to BOTH the capability and the action (no 3× repetition). */
|
|
40
|
+
tags?: string[];
|
|
41
|
+
/** The outcome_template id wired as the action's `on_success`. Defaults to `<actionId>/outcome`. */
|
|
42
|
+
outcomeTemplateId?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface EmitSpellOptions {
|
|
46
|
+
/**
|
|
47
|
+
* The catalog `entity_definition.entity_def_id` set. When provided, `emitSpell`
|
|
48
|
+
* asserts the `srd/spell/*` capability binds to a matching catalog entity (see
|
|
49
|
+
* `assertSpellCatalogBinding`). Omit to skip the check (e.g. when intentionally
|
|
50
|
+
* reusing an externally-authored capability).
|
|
51
|
+
*/
|
|
52
|
+
catalogEntityIds?: Iterable<string>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Assert a spell capability binds to a catalog entity_definition of the SAME id (#835).
|
|
57
|
+
*
|
|
58
|
+
* Throws when `capabilityId` is a `srd/spell/*` identity with no matching catalog entity
|
|
59
|
+
* in `knownEntityIds` — the author-time form of the validator's MF-VAL-264 convention
|
|
60
|
+
* warning, surfaced as an immediate error where the spell is authored instead of a
|
|
61
|
+
* post-hoc merged-bundle warning. Non-`srd/spell/*` ids (synthetic consumer affordances,
|
|
62
|
+
* monster actions, routing variants) are never asserted — they legitimately have no
|
|
63
|
+
* catalog entity, exactly the carve-out MF-VAL-264 keeps non-fatal.
|
|
64
|
+
*/
|
|
65
|
+
export function assertSpellCatalogBinding(
|
|
66
|
+
capabilityId: string,
|
|
67
|
+
knownEntityIds: Iterable<string>,
|
|
68
|
+
): void {
|
|
69
|
+
if (!capabilityId.startsWith(SPELL_CATALOG_PREFIX)) return;
|
|
70
|
+
const set =
|
|
71
|
+
knownEntityIds instanceof Set ? (knownEntityIds as Set<string>) : new Set(knownEntityIds);
|
|
72
|
+
if (!set.has(capabilityId)) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
`emitSpell: capability '${capabilityId}' has no matching catalog entity_definition with the same id. ` +
|
|
75
|
+
`A catalog spell is ONE identity (#835): author the entity_definition '${capabilityId}' before binding ` +
|
|
76
|
+
`behavior to it, or use a non-srd/spell capability id for a synthetic affordance.`,
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Build the identity-binding rows for one catalog spell from a single declaration. */
|
|
82
|
+
export function emitSpell(input: EmitSpellInput, opts: EmitSpellOptions = {}): SpellIdentityRows {
|
|
83
|
+
if (opts.catalogEntityIds) assertSpellCatalogBinding(input.capabilityId, opts.catalogEntityIds);
|
|
84
|
+
const outcome = input.outcomeTemplateId ?? `${input.actionId}/outcome`;
|
|
85
|
+
const tags = input.tags ?? [];
|
|
86
|
+
const tagRows = (idKey: "capability_id" | "action_id", idValue: string) =>
|
|
87
|
+
tags.map((tag) => ({ [idKey]: idValue, tag, bundle_id: input.bundleId, source: "manifest" }));
|
|
88
|
+
return {
|
|
89
|
+
capability_definitions: [
|
|
90
|
+
{
|
|
91
|
+
capability_id: input.capabilityId,
|
|
92
|
+
bundle_id: input.bundleId,
|
|
93
|
+
actor_kind: "entity",
|
|
94
|
+
display_name: input.displayName,
|
|
95
|
+
description: input.description ?? "",
|
|
96
|
+
},
|
|
97
|
+
],
|
|
98
|
+
capability_definition_tag: tagRows("capability_id", input.capabilityId),
|
|
99
|
+
action_definitions: [
|
|
100
|
+
{
|
|
101
|
+
action_id: input.actionId,
|
|
102
|
+
bundle_id: input.bundleId,
|
|
103
|
+
required_capability: input.capabilityId,
|
|
104
|
+
on_success: outcome,
|
|
105
|
+
display_name: input.displayName,
|
|
106
|
+
},
|
|
107
|
+
],
|
|
108
|
+
action_definition_tag: tagRows("action_id", input.actionId),
|
|
109
|
+
outcome_templates: [
|
|
110
|
+
{
|
|
111
|
+
outcome_template_id: outcome,
|
|
112
|
+
bundle_id: input.bundleId,
|
|
113
|
+
display_name: input.actionId,
|
|
114
|
+
outcome_bool: true,
|
|
115
|
+
manipulation_action_id: input.actionId,
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Manifest-read source for `./ref-tags.ts`'s caller-supplied `RefTagFamily[]`
|
|
2
|
+
// argument (`tag-vocabulary-declaration` change, design.md Decisions 1/3;
|
|
3
|
+
// `openspec/changes/tag-vocabulary-declaration/`). Every existing caller of
|
|
4
|
+
// `lintManifest`'s `dangling-ref-tag` rule and `refTagOutboundRefs` hand-writes
|
|
5
|
+
// its own `RefTagFamily[]` today (`@spellkave/srd-cc`'s `ref-tag-families.ts`
|
|
6
|
+
// is the first, and at time of writing only, such declaration — see `./ref-
|
|
7
|
+
// tags.ts`'s own header). This module adds a SECOND source for that same
|
|
8
|
+
// argument: a bundle's own manifest-declared `[[bundle.tag_prefixes]]` rows
|
|
9
|
+
// (`crates/spellkave-schema`'s `TagPrefixDeclaration`). It does not change
|
|
10
|
+
// `RefTagFamily`'s shape or retire the hand-written-array path — a content
|
|
11
|
+
// bundle may still declare its own family list by hand; this is an
|
|
12
|
+
// additional, additive source a caller can use instead.
|
|
13
|
+
|
|
14
|
+
import type { RefTagFamily } from "./ref-tags";
|
|
15
|
+
|
|
16
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
17
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function nonEmptyString(row: Record<string, unknown>, key: string): string | undefined {
|
|
21
|
+
const value = row[key];
|
|
22
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Builds the `RefTagFamily[]` argument `lintManifest`'s `dangling-ref-tag`
|
|
27
|
+
* rule and `inspection.ts`'s `refTagOutboundRefs` already accept, sourced
|
|
28
|
+
* from every `[[bundles]]` row's own `tag_prefixes` entries in `manifest`.
|
|
29
|
+
*
|
|
30
|
+
* **Scope: BundleScope.** Consumers filter manifest-derived families through
|
|
31
|
+
* the tagging row's `bundle_id` dependency closure before prefix selection;
|
|
32
|
+
* legacy hand-supplied families remain eligible for backward compatibility.
|
|
33
|
+
*
|
|
34
|
+
* **Only ref-semantics-complete entries become a family.** A `tag_prefixes`
|
|
35
|
+
* entry declaring a bare namespace (`target_kind`/`natural_key_field` both
|
|
36
|
+
* absent) is namespace-only metadata for Slice B's undeclared-prefix warning
|
|
37
|
+
* (`spellkave-validate`) — it carries nothing `RefTagFamily` (a ref-
|
|
38
|
+
* *resolution* mechanism) can act on, so it contributes no entry here. A
|
|
39
|
+
* manifest declaring no ref-semantics `tag_prefixes` anywhere returns `[]` —
|
|
40
|
+
* the exact zero-default behavior every caller already gets today when it
|
|
41
|
+
* passes no families at all, not a regression (`./lint.ts`'s own
|
|
42
|
+
* `LintManifestOptions.refTagFamilies` doc comment).
|
|
43
|
+
*
|
|
44
|
+
* **Sorted longest-`prefix`-first** (design.md Decision 2/3's "the longest
|
|
45
|
+
* matching declared prefix wins" specificity rule, restated for this TS
|
|
46
|
+
* mechanism): a bundle declaring BOTH a `"srd"` and a `"srd.ability"` ref-
|
|
47
|
+
* typed prefix puts the `"srd.ability."` family ahead of `"srd."` in the
|
|
48
|
+
* returned array, so {@link resolveTagPrefixFamily} below — which takes the
|
|
49
|
+
* FIRST matching entry — prefers the more specific declaration for any tag
|
|
50
|
+
* that could match both.
|
|
51
|
+
*/
|
|
52
|
+
export function manifestTagPrefixFamilies(manifest: Record<string, unknown>): RefTagFamily[] {
|
|
53
|
+
const bundles = manifest.bundles;
|
|
54
|
+
if (!Array.isArray(bundles)) return [];
|
|
55
|
+
const families: RefTagFamily[] = [];
|
|
56
|
+
for (const bundle of bundles) {
|
|
57
|
+
if (!isRecord(bundle)) continue;
|
|
58
|
+
const tagPrefixes = bundle.tag_prefixes;
|
|
59
|
+
if (!Array.isArray(tagPrefixes)) continue;
|
|
60
|
+
for (const entry of tagPrefixes) {
|
|
61
|
+
if (!isRecord(entry)) continue;
|
|
62
|
+
const prefix = nonEmptyString(entry, "prefix");
|
|
63
|
+
const targetKind = nonEmptyString(entry, "target_kind");
|
|
64
|
+
const naturalKeyField = nonEmptyString(entry, "natural_key_field");
|
|
65
|
+
if (!prefix || !targetKind || !naturalKeyField) continue;
|
|
66
|
+
const bundleId = nonEmptyString(bundle, "bundle_id");
|
|
67
|
+
families.push({
|
|
68
|
+
prefix: `${prefix}.`,
|
|
69
|
+
targetKind,
|
|
70
|
+
naturalKeyField,
|
|
71
|
+
declaringBundleId: bundleId,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return families.sort(compareFamilies);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function compareOptional(a: string | undefined, b: string | undefined): number {
|
|
79
|
+
if (a === b) return 0;
|
|
80
|
+
if (a === undefined) return -1;
|
|
81
|
+
if (b === undefined) return 1;
|
|
82
|
+
return a.localeCompare(b);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Mirrors Rust's length then complete declaration-key tie-break. */
|
|
86
|
+
function compareFamilies(a: RefTagFamily, b: RefTagFamily): number {
|
|
87
|
+
return (
|
|
88
|
+
b.prefix.length - a.prefix.length ||
|
|
89
|
+
compareOptional(a.declaringBundleId, b.declaringBundleId) ||
|
|
90
|
+
a.prefix.localeCompare(b.prefix) ||
|
|
91
|
+
a.targetKind.localeCompare(b.targetKind) ||
|
|
92
|
+
a.naturalKeyField.localeCompare(b.naturalKeyField)
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Resolve the single family governing `tag` under design.md's "longest
|
|
98
|
+
* matching declared prefix wins" rule: the first entry in `families` whose
|
|
99
|
+
* `prefix` `tag` starts with. Correct as long as `families` is sorted
|
|
100
|
+
* longest-prefix-first (as {@link manifestTagPrefixFamilies} returns it) —
|
|
101
|
+
* callers building their own list some other way must sort it first.
|
|
102
|
+
* Returns `undefined` when no declared family matches `tag` at all.
|
|
103
|
+
*/
|
|
104
|
+
export function resolveTagPrefixFamily(
|
|
105
|
+
tag: string,
|
|
106
|
+
families: readonly RefTagFamily[],
|
|
107
|
+
): RefTagFamily | undefined {
|
|
108
|
+
return families.filter((family) => tag.startsWith(family.prefix)).sort(compareFamilies)[0];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Families visible to a tagging row. Manifest declarations obey BundleScope;
|
|
112
|
+
* legacy hand-supplied families (no declaring bundle) remain globally eligible. */
|
|
113
|
+
export function visibleRefTagFamilies(
|
|
114
|
+
manifest: Record<string, unknown>,
|
|
115
|
+
taggingBundleId: string | undefined,
|
|
116
|
+
families: readonly RefTagFamily[],
|
|
117
|
+
): readonly RefTagFamily[] {
|
|
118
|
+
if (taggingBundleId === undefined)
|
|
119
|
+
return families.filter((family) => family.declaringBundleId === undefined);
|
|
120
|
+
const visible = bundleScope(manifest, taggingBundleId);
|
|
121
|
+
return families.filter(
|
|
122
|
+
(family) => family.declaringBundleId === undefined || visible.has(family.declaringBundleId),
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Declaring bundle plus its transitive dependencies, matching Rust BundleScope. */
|
|
127
|
+
export function bundleScope(manifest: Record<string, unknown>, bundleId: string): Set<string> {
|
|
128
|
+
const byId = new Map<string, Record<string, unknown>>();
|
|
129
|
+
for (const bundle of Array.isArray(manifest.bundles) ? manifest.bundles : []) {
|
|
130
|
+
if (!isRecord(bundle)) continue;
|
|
131
|
+
const id = nonEmptyString(bundle, "bundle_id");
|
|
132
|
+
if (id) byId.set(id, bundle);
|
|
133
|
+
}
|
|
134
|
+
const visible = new Set<string>();
|
|
135
|
+
const visit = (id: string) => {
|
|
136
|
+
if (visible.has(id)) return;
|
|
137
|
+
visible.add(id);
|
|
138
|
+
const deps = byId.get(id)?.depends_on;
|
|
139
|
+
if (Array.isArray(deps)) for (const dep of deps) if (typeof dep === "string") visit(dep);
|
|
140
|
+
};
|
|
141
|
+
visit(bundleId);
|
|
142
|
+
return visible;
|
|
143
|
+
}
|