@apifuse/provider-sdk 2.2.0-beta.29 → 2.2.0-beta.30

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/dist/types.d.ts CHANGED
@@ -1558,6 +1558,26 @@ export interface ProviderChoiceBindingOptions {
1558
1558
  connection?: boolean;
1559
1559
  credentialKeys?: readonly string[];
1560
1560
  }
1561
+ export type ProviderChoiceConsumeMode = "never" | "on-parse" | "explicit";
1562
+ export type ProviderChoiceConsumeResult = {
1563
+ readonly status: "consumed";
1564
+ } | {
1565
+ readonly status: "already-consumed";
1566
+ } | {
1567
+ readonly status: "unsupported";
1568
+ };
1569
+ export type ProviderChoiceExplicitParseResult = {
1570
+ readonly status: "active";
1571
+ readonly payload: Record<string, unknown>;
1572
+ /** Stable, opaque key for provider-owned idempotency records. */
1573
+ readonly replayKey: string;
1574
+ /** Atomically claims a word token. Legacy managed tokens report unsupported. */
1575
+ consume(): Promise<ProviderChoiceConsumeResult>;
1576
+ } | {
1577
+ readonly status: "consumed";
1578
+ /** Use this key to read the provider-owned result before returning an error. */
1579
+ readonly replayKey: string;
1580
+ };
1561
1581
  export type ProviderChoiceStorageOptions = {
1562
1582
  readonly mode: "inline";
1563
1583
  } | {
@@ -1585,6 +1605,8 @@ export interface ProviderChoiceIssueOptions<TPayload extends Record<string, unkn
1585
1605
  ttlMs: number;
1586
1606
  nowMs?: number;
1587
1607
  bind?: ProviderChoiceBindingOptions;
1608
+ /** Server storage only: standard emits four words; high emits five. */
1609
+ strength?: "standard" | "high";
1588
1610
  storage?: ProviderChoiceStorageOptions;
1589
1611
  }
1590
1612
  export interface ProviderChoiceParseOptions {
@@ -1596,6 +1618,8 @@ export interface ProviderChoiceParseOptions {
1596
1618
  futureToleranceMs?: number;
1597
1619
  bind?: ProviderChoiceBindingOptions;
1598
1620
  storage?: ProviderChoiceStorageOptions;
1621
+ /** Defaults to never, matching legacy managed-token parse semantics. */
1622
+ consume?: ProviderChoiceConsumeMode;
1599
1623
  }
1600
1624
  export interface ProviderChoiceContext {
1601
1625
  issue<TPayload extends Record<string, unknown>>(options: ProviderChoiceIssueOptions<TPayload> & {
@@ -1614,6 +1638,9 @@ export interface ProviderChoiceContext {
1614
1638
  }>;
1615
1639
  }): string | Promise<string>;
1616
1640
  issue<TPayload extends Record<string, unknown>>(options: ProviderChoiceIssueOptions<TPayload>): string | Promise<string>;
1641
+ parse(options: ProviderChoiceParseOptions & {
1642
+ readonly consume: "explicit";
1643
+ }): Promise<ProviderChoiceExplicitParseResult>;
1617
1644
  parse(options: ProviderChoiceParseOptions & {
1618
1645
  readonly storage?: {
1619
1646
  readonly mode: "inline";
@@ -1629,7 +1656,7 @@ export interface ProviderChoiceContext {
1629
1656
  readonly mode: "auto";
1630
1657
  }>;
1631
1658
  }): Record<string, unknown> | Promise<Record<string, unknown>>;
1632
- parse(options: ProviderChoiceParseOptions): Record<string, unknown>;
1659
+ parse(options: ProviderChoiceParseOptions): Record<string, unknown> | Promise<Record<string, unknown> | ProviderChoiceExplicitParseResult>;
1633
1660
  }
1634
1661
  export interface ContextScratchpad {
1635
1662
  get(key: string): unknown;
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.2.0-beta.29",
2
+ "version": "2.2.0-beta.30",
3
3
  "name": "@apifuse/provider-sdk",
4
4
  "private": false,
5
5
  "type": "module",
package/src/index.ts CHANGED
@@ -291,7 +291,10 @@ export type {
291
291
  ProviderCacheResponseMeta,
292
292
  ProviderCacheResult,
293
293
  ProviderChoiceBindingOptions,
294
+ ProviderChoiceConsumeMode,
295
+ ProviderChoiceConsumeResult,
294
296
  ProviderChoiceContext,
297
+ ProviderChoiceExplicitParseResult,
295
298
  ProviderChoiceIssueOptions,
296
299
  ProviderChoiceParseOptions,
297
300
  ProviderChallenge,
package/src/provider.ts CHANGED
@@ -135,7 +135,10 @@ export type {
135
135
  OperationTransport,
136
136
  ProviderAccessVisibility,
137
137
  ProviderChoiceBindingOptions,
138
+ ProviderChoiceConsumeMode,
139
+ ProviderChoiceConsumeResult,
138
140
  ProviderChoiceContext,
141
+ ProviderChoiceExplicitParseResult,
139
142
  ProviderChoiceIssueOptions,
140
143
  ProviderChoiceParseOptions,
141
144
  ProviderContext,
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Official EFF Short Wordlist #2, embedded unchanged from:
3
+ * https://www.eff.org/files/2016/09/08/eff_short_wordlist_2_0.txt
4
+ *
5
+ * The source's dice-roll column is intentionally omitted; word order is preserved.
6
+ */
7
+ const EFF_SHORT_WORDLIST_2_TEXT = `
8
+ aardvark abandoned abbreviate abdomen abhorrence abiding abnormal abrasion absorbing abundant abyss
9
+ academy accountant acetone achiness acid acoustics acquire acrobat actress acuteness aerosol
10
+ aesthetic affidavit afloat afraid aftershave again agency aggressor aghast agitate agnostic
11
+ agonizing agreeing aidless aimlessly ajar alarmclock albatross alchemy alfalfa algae aliens
12
+ alkaline almanac alongside alphabet already also altitude aluminum always amazingly ambulance
13
+ amendment amiable ammunition amnesty amoeba amplifier amuser anagram anchor android anesthesia
14
+ angelfish animal anklet announcer anonymous answer antelope anxiety anyplace aorta apartment apnea
15
+ apostrophe apple apricot aquamarine arachnid arbitrate ardently arena argument aristocrat armchair
16
+ aromatic arrowhead arsonist artichoke asbestos ascend aseptic ashamed asinine asleep asocial
17
+ asparagus astronaut asymmetric atlas atmosphere atom atrocious attic atypical auctioneer auditorium
18
+ augmented auspicious automobile auxiliary avalanche avenue aviator avocado awareness awhile awkward
19
+ awning awoke axially azalea babbling backpack badass bagpipe bakery balancing bamboo banana
20
+ barracuda basket bathrobe bazooka blade blender blimp blouse blurred boatyard bobcat body bogusness
21
+ bohemian boiler bonnet boots borough bossiness bottle bouquet boxlike breath briefcase broom
22
+ brushes bubblegum buckle buddhist buffalo bullfrog bunny busboy buzzard cabin cactus cadillac
23
+ cafeteria cage cahoots cajoling cakewalk calculator camera canister capsule carrot cashew cathedral
24
+ caucasian caviar ceasefire cedar celery cement census ceramics cesspool chalkboard cheesecake
25
+ chimney chlorine chopsticks chrome chute cilantro cinnamon circle cityscape civilian clay clergyman
26
+ clipboard clock clubhouse coathanger cobweb coconut codeword coexistent coffeecake cognitive
27
+ cohabitate collarbone computer confetti copier cornea cosmetics cotton couch coverless coyote
28
+ coziness crawfish crewmember crib croissant crumble crystal cubical cucumber cuddly cufflink
29
+ cuisine culprit cup curry cushion cuticle cybernetic cyclist cylinder cymbal cynicism cypress
30
+ cytoplasm dachshund daffodil dagger dairy dalmatian dandelion dartboard dastardly datebook daughter
31
+ dawn daytime dazzler dealer debris decal dedicate deepness defrost degree dehydrator deliverer
32
+ democrat dentist deodorant depot deranged desktop detergent device dexterity diamond dibs
33
+ dictionary diffuser digit dilated dimple dinnerware dioxide diploma directory dishcloth ditto
34
+ dividers dizziness doctor dodge doll dominoes donut doorstep dorsal double downstairs dozed
35
+ drainpipe dresser driftwood droppings drum dryer dubiously duckling duffel dugout dumpster duplex
36
+ durable dustpan dutiful duvet dwarfism dwelling dwindling dynamite dyslexia eagerness earlobe easel
37
+ eavesdrop ebook eccentric echoless eclipse ecosystem ecstasy edged editor educator eelworm eerie
38
+ effects eggnog egomaniac ejection elastic elbow elderly elephant elfishly eliminator elk elliptical
39
+ elongated elsewhere elusive elves emancipate embroidery emcee emerald emission emoticon emperor
40
+ emulate enactment enchilada endorphin energy enforcer engine enhance enigmatic enjoyably enlarged
41
+ enormous enquirer enrollment ensemble entryway enunciate envoy enzyme epidemic equipment erasable
42
+ ergonomic erratic eruption escalator eskimo esophagus espresso essay estrogen etching eternal
43
+ ethics etiquette eucalyptus eulogy euphemism euthanize evacuation evergreen evidence evolution exam
44
+ excerpt exerciser exfoliate exhale exist exorcist explode exquisite exterior exuberant fabric
45
+ factory faded failsafe falcon family fanfare fasten faucet favorite feasibly february federal
46
+ feedback feigned feline femur fence ferret festival fettuccine feudalist feverish fiberglass
47
+ fictitious fiddle figurine fillet finalist fiscally fixture flashlight fleshiness flight florist
48
+ flypaper foamless focus foggy folksong fondue footpath fossil fountain fox fragment freeway fridge
49
+ frosting fruit fryingpan gadget gainfully gallstone gamekeeper gangway garlic gaslight gathering
50
+ gauntlet gearbox gecko gem generator geographer gerbil gesture getaway geyser ghoulishly gibberish
51
+ giddiness giftshop gigabyte gimmick giraffe giveaway gizmo glasses gleeful glisten glove glucose
52
+ glycerin gnarly gnomish goatskin goggles goldfish gong gooey gorgeous gosling gothic gourmet
53
+ governor grape greyhound grill groundhog grumbling guacamole guerrilla guitar gullible gumdrop
54
+ gurgling gusto gutless gymnast gynecology gyration habitat hacking haggard haiku halogen hamburger
55
+ handgun happiness hardhat hastily hatchling haughty hazelnut headband hedgehog hefty heinously
56
+ helmet hemoglobin henceforth herbs hesitation hexagon hubcap huddling huff hugeness hullabaloo
57
+ human hunter hurricane hushing hyacinth hybrid hydrant hygienist hypnotist ibuprofen icepack icing
58
+ iconic identical idiocy idly igloo ignition iguana illuminate imaging imbecile imitator immigrant
59
+ imprint iodine ionosphere ipad iphone iridescent irksome iron irrigation island isotope issueless
60
+ italicize itemizer itinerary itunes ivory jabbering jackrabbit jaguar jailhouse jalapeno jamboree
61
+ janitor jarring jasmine jaundice jawbreaker jaywalker jazz jealous jeep jelly jeopardize jersey
62
+ jetski jezebel jiffy jigsaw jingling jobholder jockstrap jogging john joinable jokingly journal
63
+ jovial joystick jubilant judiciary juggle juice jujitsu jukebox jumpiness junkyard juror justifying
64
+ juvenile kabob kamikaze kangaroo karate kayak keepsake kennel kerosene ketchup khaki kickstand
65
+ kilogram kimono kingdom kiosk kissing kite kleenex knapsack kneecap knickers koala krypton
66
+ laboratory ladder lakefront lantern laptop laryngitis lasagna latch laundry lavender laxative
67
+ lazybones lecturer leftover leggings leisure lemon length leopard leprechaun lettuce leukemia
68
+ levers lewdness liability library licorice lifeboat lightbulb likewise lilac limousine lint lioness
69
+ lipstick liquid listless litter liverwurst lizard llama luau lubricant lucidity ludicrous luggage
70
+ lukewarm lullaby lumberjack lunchbox luridness luscious luxurious lyrics macaroni maestro magazine
71
+ mahogany maimed majority makeover malformed mammal mango mapmaker marbles massager matchstick
72
+ maverick maximum mayonnaise moaning mobilize moccasin modify moisture molecule momentum monastery
73
+ moonshine mortuary mosquito motorcycle mousetrap movie mower mozzarella muckiness mudflow mugshot
74
+ mule mummy mundane muppet mural mustard mutation myriad myspace myth nail namesake nanosecond
75
+ napkin narrator nastiness natives nautically navigate nearest nebula nectar nefarious negotiator
76
+ neither nemesis neoliberal nephew nervously nest netting neuron nevermore nextdoor nicotine niece
77
+ nimbleness nintendo nirvana nuclear nugget nuisance nullify numbing nuptials nursery nutcracker
78
+ nylon oasis oat obediently obituary object obliterate obnoxious observer obtain obvious occupation
79
+ oceanic octopus ocular office oftentimes oiliness ointment older olympics omissible omnivorous
80
+ oncoming onion onlooker onstage onward onyx oomph opaquely opera opium opossum opponent optical
81
+ opulently oscillator osmosis ostrich otherwise ought outhouse ovation oven owlish oxford oxidize
82
+ oxygen oyster ozone pacemaker padlock pageant pajamas palm pamphlet pantyhose paprika parakeet
83
+ passport patio pauper pavement payphone pebble peculiarly pedometer pegboard pelican penguin peony
84
+ pepperoni peroxide pesticide petroleum pewter pharmacy pheasant phonebook phrasing physician plank
85
+ pledge plotted plug plywood pneumonia podiatrist poetic pogo poison poking policeman poncho popcorn
86
+ porcupine postcard poultry powerboat prairie pretzel princess propeller prune pry pseudo psychopath
87
+ publisher pucker pueblo pulley pumpkin punchbowl puppy purse pushup putt puzzle pyramid python
88
+ quarters quesadilla quilt quote racoon radish ragweed railroad rampantly rancidity rarity raspberry
89
+ ravishing rearrange rebuilt receipt reentry refinery register rehydrate reimburse rejoicing
90
+ rekindle relic remote renovator reopen reporter request rerun reservoir retriever reunion revolver
91
+ rewrite rhapsody rhetoric rhino rhubarb rhyme ribbon riches ridden rigidness rimmed riptide riskily
92
+ ritzy riverboat roamer robe rocket romancer ropelike rotisserie roundtable royal rubber rudderless
93
+ rugby ruined rulebook rummage running rupture rustproof sabotage sacrifice saddlebag saffron
94
+ sainthood saltshaker samurai sandworm sapphire sardine sassy satchel sauna savage saxophone scarf
95
+ scenario schoolbook scientist scooter scrapbook sculpture scythe secretary sedative segregator
96
+ seismology selected semicolon senator septum sequence serpent sesame settler severely shack shelf
97
+ shirt shovel shrimp shuttle shyness siamese sibling siesta silicon simmering singles sisterhood
98
+ sitcom sixfold sizable skateboard skeleton skies skulk skylight slapping sled slingshot sloth
99
+ slumbering smartphone smelliness smitten smokestack smudge snapshot sneezing sniff snowsuit
100
+ snugness speakers sphinx spider splashing sponge sprout spur spyglass squirrel statue steamboat
101
+ stingray stopwatch strawberry student stylus suave subway suction suds suffocate sugar suitcase
102
+ sulphur superstore surfer sushi swan sweatshirt swimwear sword sycamore syllable symphony synagogue
103
+ syringes systemize tablespoon taco tadpole taekwondo tagalong takeout tallness tamale tanned
104
+ tapestry tarantula tastebud tattoo tavern thaw theater thimble thorn throat thumb thwarting tiara
105
+ tidbit tiebreaker tiger timid tinsel tiptoeing tirade tissue tractor tree tripod trousers trucks
106
+ tryout tubeless tuesday tugboat tulip tumbleweed tupperware turtle tusk tutorial tuxedo tweezers
107
+ twins tyrannical ultrasound umbrella umpire unarmored unbuttoned uncle underwear unevenness
108
+ unflavored ungloved unhinge unicycle unjustly unknown unlocking unmarked unnoticed unopened unpaved
109
+ unquenched unroll unscrewing untied unusual unveiled unwrinkled unyielding unzip upbeat upcountry
110
+ update upfront upgrade upholstery upkeep upload uppercut upright upstairs uptown upwind uranium
111
+ urban urchin urethane urgent urologist username usher utensil utility utmost utopia utterance
112
+ vacuum vagrancy valuables vanquished vaporizer varied vaseline vegetable vehicle velcro vendor
113
+ vertebrae vestibule veteran vexingly vicinity videogame viewfinder vigilante village vinegar violin
114
+ viperfish virus visor vitamins vivacious vixen vocalist vogue voicemail volleyball voucher voyage
115
+ vulnerable waffle wagon wakeup walrus wanderer wasp water waving wheat whisper wholesaler wick
116
+ widow wielder wifeless wikipedia wildcat windmill wipeout wired wishbone wizardry wobbliness
117
+ wolverine womb woolworker workbasket wound wrangle wreckage wristwatch wrongdoing xerox xylophone
118
+ yacht yahoo yard yearbook yesterday yiddish yield yo-yo yodel yogurt yuppie zealot zebra zeppelin
119
+ zestfully zigzagged zillion zipping zirconium zodiac zombie zookeeper zucchini
120
+ `;
121
+
122
+ export const CHOICE_WORDLIST_SIZE = 1_296;
123
+ export const CHOICE_WORD_ENTROPY_BITS = Math.log2(CHOICE_WORDLIST_SIZE);
124
+ export const STANDARD_CHOICE_WORD_COUNT = 4;
125
+ export const HIGH_CHOICE_WORD_COUNT = 5;
126
+ export const STANDARD_CHOICE_ENTROPY_BITS = STANDARD_CHOICE_WORD_COUNT * CHOICE_WORD_ENTROPY_BITS;
127
+ export const HIGH_CHOICE_ENTROPY_BITS = HIGH_CHOICE_WORD_COUNT * CHOICE_WORD_ENTROPY_BITS;
128
+
129
+ export const EFF_SHORT_WORDLIST_2: readonly string[] = Object.freeze(
130
+ EFF_SHORT_WORDLIST_2_TEXT.trim().split(/\s+/),
131
+ );
132
+
133
+ const EFF_SHORT_WORD_SET: ReadonlySet<string> = new Set(EFF_SHORT_WORDLIST_2);
134
+
135
+ export function choiceWordAt(index: number): string {
136
+ const word = EFF_SHORT_WORDLIST_2[index];
137
+ if (word === undefined) {
138
+ throw new RangeError(`Choice word index is out of range: ${index}`);
139
+ }
140
+ return word;
141
+ }
142
+
143
+ export function isChoiceWord(value: string): boolean {
144
+ return EFF_SHORT_WORD_SET.has(value);
145
+ }